萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP GD 圖形繪製入門:動態生成 PNG 圖片完整教學

PHP 內建的 GD 函式庫讓你無需外部工具,即可在伺服器端動態生成圖表、驗證碼、水印、縮圖等圖片。本文從零開始,帶你建立第一張 PHP 生成的 PNG 圖片,並解析核心繪圖流程與常用函數。

環境需求確認

<?php
// 檢查 GD 支援
if (!extension_loaded('gd')) {
    die('GD 擴展未載入,請安裝 php-gd');
}
$info = gd_info();
echo "GD 版本:{$info['GD Version']}\n";
echo "PNG 支援:" . ($info['PNG Support'] ? '是' : '否') . "\n";
echo "FreeType 支援:" . ($info['FreeType Support'] ? '是' : '否') . "\n";

核心繪圖流程五步驟

  1. 建立畫布:imagecreatetruecolor()(真彩色)或 imagecreate()(調色盤模式,已過時)。
  2. 分配顏色:imagecolorallocate() 定義 RGB 顏色,第一個分配的顏色會成為背景色。
  3. 繪製圖形/文字:使用各種 image* 函數繪製線條、矩形、橢圓、文字等。
  4. 輸出圖片:發送正確的 Content-Type 標頭,呼叫 imagepng()/imagejpeg() 輸出。
  5. 釋放資源:imagedestroy() 釋放記憶體,長時間運行的腳本特別重要。

實作範例:繪製紅圓與白底畫布

<?php
// 1. 設定輸出標頭(必須在任何輸出前)
header('Content-Type: image/png');

// 2. 建立 400x300 真彩色畫布
$width = 400;
$height = 300;
$img = imagecreatetruecolor($width, $height);

// 3. 分配顏色(第一個為背景色)
$white = imagecolorallocate($img, 255, 255, 255); // 白色背景
$red   = imagecolorallocate($img, 255, 0, 0);       // 紅色

// 4. 填滿背景(可選,imagecreatetruecolor 預設黑底)
imagefill($img, 0, 0, $white);

// 5. 繪製實心橢圓:中心(200,150)、寬高 100x80
imageellipse($img, 200, 150, 100, 80, $red);

// 6. 繪製邊框矩形
$blue = imagecolorallocate($img, 0, 0, 255);
imagerectangle($img, 50, 50, 350, 250, $blue);

// 7. 輸出 PNG
imagepng($img);

// 8. 釋放記憶體
imagedestroy($img);

PHP GD 繪圖範例輸出

常用繪圖函數速查

函數用途關鍵參數
imagesetpixel()繪製單一像素$x, $y, $color
imageline()繪製直線$x1, $y1, $x2, $y2, $color
imagerectangle()繪製矩形邊框$x1, $y1, $x2, $y2, $color
imagefilledrectangle()繪製實心矩形$x1, $y1, $x2, $y2, $color
imageellipse()繪製橢圓/圓邊框$cx, $cy, $w, $h, $color
imagefilledellipse()繪製實心橢圓/圓$cx, $cy, $w, $h, $color
imagepolygon()繪製多邊形邊框$points 陣列, $num_points, $color
imagefilledpolygon()繪製實心多邊形$points 陣列, $num_points, $color
imagestring()繪製內建字型文字(僅 ASCII)$font(1-5), $x, $y, $string, $color
imagettftext()繪製 TrueType 字型文字(支援中文)$size, $angle, $x, $y, $color, $fontfile, $text

進階技巧:抗鋸齒與透明度

<?php
$img = imagecreatetruecolor(200, 200);

// 啟用 Alpha 混合(支援半透明)
imagealphablending($img, true);
imagesavealpha($img, true);

// 建立半透明紅色 (127 為完全透明,0 為不透明)
$transparentRed = imagecolorallocatealpha($img, 255, 0, 0, 64);

// 繪製半透明圓形重疊效果
imagefilledellipse($img, 80, 80, 100, 100, $transparentRed);
imagefilledellipse($img, 120, 120, 100, 100, imagecolorallocatealpha($img, 0, 0, 255, 64));

header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);

常見問題排查

  1. 輸出亂碼/圖片損壞:檢查是否有 BOM、空白字元、錯誤訊息輸出在 header() 之前。建議純 PHP 檔案省略結尾 ?>。
  2. 中文顯示方框:必須使用 imagettftext() 搭配 .ttf 字體檔(如微軟正黑體、思源黑體)。
  3. 記憶體耗盡:大尺寸圖片佔用大量記憶體,處理完立即 imagedestroy();必要時調整 memory_limit。
  4. imagepng() 品質參數:imagepng($img, null, 9) 壓縮等級 0-9(預設 6),不影響畫質僅影響檔案大小與壓縮時間。

實戰應用場景

  • 動態圖表:結合資料庫統計數據,繪製長條圖、折線圖、圓餅圖。
  • 驗證碼生成:隨機字串 + 干擾線/點 + 扭曲變形。
  • 圖片水印:imagecopy() 疊加 Logo 或文字浮水印。
  • 縮圖裁切:imagecopyresampled() 高品質縮放裁切。
  • 資料視覺化報表:定時生成圖片供前端直接 <img> 引用,減輕前端渲染負擔。

GD 函式庫雖然不如 ImageMagick 功能豐富,但零依賴、效能優異,足以應付大多數 Web 圖片生成需求。掌握基礎繪圖流程後,你可以嘗試實作一個動態統計圖表或專屬驗證碼系統!

copyright © 萬盛學電腦網 all rights reserved