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";
imagecreatetruecolor()(真彩色)或 imagecreate()(調色盤模式,已過時)。imagecolorallocate() 定義 RGB 顏色,第一個分配的顏色會成為背景色。image* 函數繪製線條、矩形、橢圓、文字等。Content-Type 標頭,呼叫 imagepng()/imagejpeg() 輸出。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);

| 函數 | 用途 | 關鍵參數 |
|---|---|---|
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);
header() 之前。建議純 PHP 檔案省略結尾 ?>。imagettftext() 搭配 .ttf 字體檔(如微軟正黑體、思源黑體)。imagedestroy();必要時調整 memory_limit。imagepng() 品質參數:imagepng($img, null, 9) 壓縮等級 0-9(預設 6),不影響畫質僅影響檔案大小與壓縮時間。imagecopy() 疊加 Logo 或文字浮水印。imagecopyresampled() 高品質縮放裁切。<img> 引用,減輕前端渲染負擔。GD 函式庫雖然不如 ImageMagick 功能豐富,但零依賴、效能優異,足以應付大多數 Web 圖片生成需求。掌握基礎繪圖流程後,你可以嘗試實作一個動態統計圖表或專屬驗證碼系統!