前言
GD 庫是 PHP 內建圖形處理擴展,函數超百個。本文按功能分類整理常用函數,並給出面向對象封裝建議,作為開發速查手冊。
1. 圖像創建與載入
| 函數 | 說明 | 返回 |
| imagecreate($w, $h) | 基於調色板(256色)創建畫布 | resource |
| imagecreatetruecolor($w, $h) | 真彩色畫布(無顏色限制,推薦) | resource |
| imagecreatefromjpeg/png/gif/wbmp/string($filename) | 從文件/字符串創建圖像資源 | resource|false |
| imagecreatefromgd2/gd2part/gd/xbm/xpm(...) | 其他格式載入 | resource|false |
2. 圖像複製與縮放
| 函數 | 說明 | 關鍵參數 |
| imagecopy($dst, $src, $dx, $dy, $sx, $sy, $sw, $sh) | 直接複製矩形區域 | 目標/源座標、寬高 |
| imagecopymerge($dst, $src, $dx, $dy, $sx, $sy, $sw, $sh, $pct) | 複製並按透明度合併 (0-100) | $pct 透明度 |
| imagecopymergegray(...) | 複製合併並轉灰度 | - |
| imagecopyresized(...) | 複製並縮放(簡易,質量一般) | - |
| imagecopyresampled(...) | 複製並重採樣縮放(高質量,推薦) | - |
3. 繪圖基元
| 分類 | 函數 | 說明 |
| 像素 | imagesetpixel($im, $x, $y, $color) | 畫單個像素 |
| imagecolorat($im, $x, $y) | 獲取像素顏色索引 |
| 線條 | imageline($im, $x1, $y1, $x2, $y2, $color) | 畫線段 |
| imagedashedline(...) | 畫虛線 |
| imagearc($im, $cx, $cy, $w, $h, $s, $e, $color) | 畫橢圓弧 |
| imagefilledarc(...) | 畫填充橢圓弧(餅圖) |
| 幾何形狀 | imagerectangle / imagefilledrectangle | 矩形/填充矩形 |
| imageellipse / imagefilledellipse | 橢圓/填充橢圓 |
| imagepolygon / imagefilledpolygon | 多邊形/填充多邊形 |
| imageopenpolygon (PHP 7+) | 開放多邊形 |
4. 文字繪製
| 函數 | 字體類型 | 特點 |
| imagestring($im, $font, $x, $y, $str, $color) | 內建點陣字體 (1-5) | 簡單、無縮放、僅 ASCII |
| imagestringup(...) | 內建點陣字體 | 垂直輸出 |
| imagettftext($im, $size, $angle, $x, $y, $color, $fontfile, $text) | TrueType (.ttf) | ✅ 主流選擇,支援縮放、旋轉、Unicode |
| imagettfbbox(...) | TrueType | 計算文本邊界框(居中對齊必需) |
| imagefttext / imagepsencodefont / imagepstext | FreeType2 / PostScript Type1 | 較少用 |
5. 顏色管理
| 函數 | 說明 |
| imagecolorallocate($im, $r, $g, $b) | 分配顏色(第一次調用設為背景色) |
| imagecolorallocatealpha($im, $r, $g, $b, $alpha) | 分配帶透明度顏色 (0不透明-127全透明) |
| imagecolorat($im, $x, $y) | 獲取像素顏色索引 |
| imagecolorsforindex($im, $index) | 索引轉 RGB 數組 |
| imagecolorexact / imagecolorclosest / imagecolorresolve | 查找/最近/解析顏色索引 |
| imagecolortransparent($im, $color) | 設置透明色 |
6. 圖像屬性獲取
| 函數 | 說明 |
| getimagesize($filename) | 返回 [寬, 高, 類型常量, 屬性字符串, bits, channels] |
| imagesx($im) / imagesy($im) | 獲取圖像資源寬/高 |
| imagefontwidth($font) / imagefontheight($font) | 內建字體寬/高 |
| image_type_to_extension($type, $include_dot) | 類型常量轉副檔名 |
| image_type_to_mime_type($type) | 類型常量轉 MIME |
7. 輸出與銷毀
| 函數 | 格式 | 說明 |
| imagejpeg($im, $filename=null, $quality=75) | JPEG | $filename=null 直接輸出瀏覽器 |
| imagepng($im, $filename=null, $quality=0-9) | PNG | $quality 壓縮級別 |
| imagegif($im, $filename=null) | GIF | 動畫需額外處理 |
| imagewbmp / imagexbm | WBMP / XBM | 無線/位圖格式 |
| imagedestroy($im) | - | ✅ 必須調用 釋放內存 |
8. 進階特效(PHP 5.5+ / 7+)
imagefilter($im, IMG_FILTER_GRAYSCALE) - 灰度
imagefilter($im, IMG_FILTER_GAUSSIAN_BLUR) - 高斯模糊
imagefilter($im, IMG_FILTER_SELECTIVE_BLUR) - 選擇性模糊
imagefilter($im, IMG_FILTER_EMBOSS) - 浮雕
imagefilter($im, IMG_FILTER_MEAN_REMOVAL) - 邊緣檢測
imagefilter($im, IMG_FILTER_SMOOTH, $weight) - 平滑
imageconvolution($im, $matrix, $div, $offset) - 自定義卷積核(銳化、邊緣增強等)
面向對象封裝建議:ImageManager 類
class ImageManager {
private $im;
private $width, $height;
public static function create(int $w, int $h, bool $trueColor = true): self {
$instance = new self();
$instance->im = $trueColor ? imagecreatetruecolor($w, $h) : imagecreate($w, $h);
$instance->width = $w; $instance->height = $h;
return $instance;
}
public static function load(string $path): self {
$info = getimagesize($path);
$func = ['', 'imagecreatefromgif', 'imagecreatefromjpeg', 'imagecreatefrompng'][$info[2]] ?? null;
if (!$func) throw new Exception("Unsupported format");
$instance = new self();
$instance->im = $func($path);
$instance->width = $info[0]; $instance->height = $info[1];
return $instance;
}
public function color(int $r, int $g, int $b, int $alpha = 0): int {
return $alpha ? imagecolorallocatealpha($this->im, $r, $g, $b, $alpha)
: imagecolorallocate($this->im, $r, $g, $b);
}
public function text(string $text, string $font, int $size, int $x, int $y, int $color, int $angle = 0): self {
imagettftext($this->im, $size, $angle, $x, $y, $color, $font, $text);
return $this;
}
public function rect(int $x1, int $y1, int $x2, int $y2, int $color, bool $fill = false): self {
$fill ? imagefilledrectangle($this->im, $x1, $y1, $x2, $y2, $color)
: imagerectangle($this->im, $x1, $y1, $x2, $y2, $color);
return $this;
}
public function save(string $path, int $quality = 90): bool {
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$func = ['jpg'=>'imagejpeg', 'jpeg'=>'imagejpeg', 'png'=>'imagepng', 'gif'=>'imagegif'][$ext] ?? null;
if (!$func) throw new Exception("Unsupported save format");
return $func($this->im, $path, $quality);
}
public function output(int $quality = 90): void {
header('Content-Type: ' . image_type_to_mime_type(IMAGETYPE_PNG));
imagepng($this->im, null, $quality);
}
public function __destruct() {
if ($this->im) imagedestroy($this->im);
}
}
// 使用
$img = ImageManager::create(200, 100);
$red = $img->color(255, 0, 0);
$white = $img->color(255, 255, 255);
$img->rect(0, 0, 199, 99, $red, true)
->text('Hello GD', 'font.ttf', 24, 20, 60, $white)
->save('output.png');
結語
GD 函數雖多,但核心常用約 30 個。掌握「創建→繪製/文字→輸出→銷毀」流程,配合 ImageManager 鏈式調用,即可優雅完成驗證碼、海報生成、圖表繪製等需求。複雜矢量/濾鏡場景建議改用 ImageMagick (Imagick 擴展)。