前言
GD 是 PHP 內建圖形處理擴展,支援 PNG、JPEG、GIF、WBMP、WebP、XBM、XPM 等格式。需安裝 php-gd 並啟用 extension=gd。現代專案建議考慮 ImageMagick (imagick) 功能更強、效能更好。
一、資訊與建立
| 函式 | 說明 |
gd_info() | 取得 GD 版本與支援格式陣列 |
getimagesize(string $filename, array &$imageinfo) | 取得圖片寬高、類型、MIME |
image_type_to_extension(int $imagetype, bool $include_dot) | 類型常數轉副檔名 |
image_type_to_mime_type(int $imagetype) | 類型常數轉 MIME |
imagecreate(int $width, int $height) | 建立調色板圖片(舊版,256 色) |
imagecreatetruecolor(int $width, int $height) | 建立真彩色圖片(推薦,1670 萬色) |
二、從檔案/字串載入
| 函式 | 格式 |
imagecreatefromjpeg | JPEG |
imagecreatefrompng | PNG(支援透明) |
imagecreatefromgif | GIF |
imagecreatefromwebp | WebP |
imagecreatefromwbmp | WBMP |
imagecreatefromxbm | XBM |
imagecreatefromxpm | XPM |
imagecreatefromstring(string $data) | 從二進位字串建立(自動偵測格式) |
imagecreatefromgd / gd2 / gd2part | GD 專有格式 |
三、色彩管理
| 函式 | 說明 |
imagecolorallocate(resource $im, r, g, b) | 分配色彩(回傳索引) |
imagecolorallocatealpha(resource $im, r, g, b, alpha) | 分配色彩+透明度 (0-127) |
imagecolorat(resource $im, x, y) | 取得像素色彩索引 |
imagecolorsforindex(resource $im, index) | 索引轉 RGB 陣列 |
imagecolorresolve(resource $im, r, g, b) | 取得最接近色彩索引(不存在則分配) |
imagecolorresolvealpha(resource $im, r, g, b, alpha) | 含透明度版 |
imagecolorexact(resource $im, r, g, b) | 精確匹配色彩索引 |
imagecolormatch(resource $palette, resource $truecolor) | 調色板圖匹配真彩色圖 |
imagecolordeallocate(resource $im, index) | 釋放色彩索引 |
imagecolortransparent(resource $im, index) | 設定透明色 |
imagecolorstotal(resource $im) | 調色板色彩總數 |
四、繪圖基礎
| 函式 | 說明 |
imagesetpixel(resource $im, x, y, color) | 畫單一像素 |
imageline(resource $im, x1, y1, x2, y2, color) | 畫直線 |
imagedashedline(resource $im, x1, y1, x2, y2, color) | 畫虛線 |
imagerectangle(resource $im, x1, y1, x2, y2, color) | 畫矩形框 |
imagefilledrectangle(resource $im, x1, y1, x2, y2, color) | 畫實心矩形 |
imagepolygon(resource $im, points, num_points, color) | 畫多邊形框 |
imagefilledpolygon(resource $im, points, num_points, color) | 畫實心多邊形 |
imageellipse(resource $im, cx, cy, w, h, color) | 畫橢圓框 |
imagefilledellipse(resource $im, cx, cy, w, h, color) | 畫實心橢圓 |
imagearc(resource $im, cx, cy, w, h, start, end, color) | 畫橢圓弧 |
imagefilledarc(resource $im, cx, cy, w, h, start, end, color, style) | 畫實心扇形 |
五、填充與樣式
| 函式 | 說明 |
imagefill(resource $im, x, y, color) | 洪水填充(從點擴散) |
imagefilltoborder(resource $im, x, y, border, color) | 填充至邊界色 |
imagesetstyle(resource $im, array $styles) | 設定線條樣式(虛線模式陣列) |
imagesetthickness(resource $im, thickness) | 設定線條粗細 |
imagesetbrush(resource $im, resource $brush) | 設定筆刷(另一張圖片) |
imagesettile(resource $im, resource $tile) | 設定磚塊填充圖案 |
六、文字繪製
| 函式 | 說明 |
imagechar(resource $im, font, x, y, char, color) | 內建字型畫單字元(水平) |
imagecharup(resource $im, font, x, y, char, color) | 內建字型畫單字元(垂直) |
imagestring(resource $im, font, x, y, string, color) | 內建字型畫字串(水平) |
imagestringup(resource $im, font, x, y, string, color) | 內建字型畫字串(垂直) |
imagettftext(resource $im, size, angle, x, y, color, fontfile, text) | TrueType 字型畫字串(支援中文、旋轉) |
imagettfbbox(resource $im, size, angle, fontfile, text) | 計算 TTF 文字邊界框 |
imagefttext / imageftbbox | FreeType2 版本(功能同 TTF) |
imagefontwidth(int $font) | 內建字型寬度 |
imagefontheight(int $font) | 內建字型高度 |
中文繪製關鍵:使用 TTF 字型
<?php
$im = imagecreatetruecolor(400, 100);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefill($im, 0, 0, $white);
// 需要 .ttf 字型檔(如微軟正黑體 msjh.ttc)
$font = __DIR__ . '/fonts/msjh.ttc';
$text = '你好,PHP GD!';
$bbox = imagettfbbox(24, 0, $font, $text);
$textWidth = $bbox[2] - $bbox[0];
$x = (400 - $textWidth) / 2;
$y = 60;
imagettftext($im, 24, 0, $x, $y, $black, $font, $text);
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
七、圖片複製與縮放
| 函式 | 說明 |
imagecopy(resource $dst, $src, dx, dy, sx, sy, w, h) | 複製區域(無縮放) |
imagecopyresized(resource $dst, $src, dx, dy, sx, sy, dw, dh, sw, sh) | 複製並縮放(品質較差) |
imagecopyresampled(resource $dst, $src, dx, dy, sx, sy, dw, dh, sw, sh) | 複製並重採樣縮放(品質佳,推薦) |
imagecopymerge(resource $dst, $src, dx, dy, sx, sy, w, h, pct) | 複製並混合透明度 (0-100) |
imagecopymergegray(resource $dst, $src, dx, dy, sx, sy, w, h, pct) | 複製並轉灰階混合 |
縮圖產生器範例
<?php
function createThumbnail(string $srcPath, string $dstPath, int $maxW, int $maxH, int $quality = 85) {
list($srcW, $srcH, $type) = getimagesize($srcPath);
$createFunc = ['', 'imagecreatefromgif', 'imagecreatefromjpeg', 'imagecreatefrompng', '', '', '', 'imagecreatefromwebp'][$type] ?? null;
if (!$createFunc) throw new Exception('Unsupported format');
$src = $createFunc($srcPath);
$ratio = min($maxW / $srcW, $maxH / $srcH);
$dstW = (int)($srcW * $ratio);
$dstH = (int)($srcH * $ratio);
$dst = imagecreatetruecolor($dstW, $dstH);
// 保持 PNG 透明
if ($type === IMAGETYPE_PNG || $type === IMAGETYPE_GIF) {
imagealphablending($dst, false);
imagesavealpha($dst, true);
$transparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
imagefill($dst, 0, 0, $transparent);
}
imagecopyresampled($dst, $src, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);
// 輸出
switch ($type) {
case IMAGETYPE_JPEG: imagejpeg($dst, $dstPath, $quality); break;
case IMAGETYPE_PNG: imagepng($dst, $dstPath, 9); break;
case IMAGETYPE_GIF: imagegif($dst, $dstPath); break;
case IMAGETYPE_WEBP: imagewebp($dst, $dstPath, $quality); break;
}
imagedestroy($src);
imagedestroy($dst);
}
八、輸出與儲存
| 函式 | 格式 |
imagejpeg(resource $im, filename, quality) | JPEG (quality 0-100) |
imagepng(resource $im, filename, compression, filters) | PNG (compression 0-9) |
imagegif(resource $im, filename) | GIF |
imagewebp(resource $im, filename, quality) | WebP (quality 0-100) |
imagewbmp(resource $im, filename, foreground) | WBMP |
imagexbm(resource $im, filename, foreground) | XBM |
imagegd / imagegd2 | GD 專有格式 |
九、進階效果
| 函式 | 說明 |
imagefilter(resource $im, filtertype, args...) | 濾鏡:灰階、銳化、邊緣偵測、高斯模糊、色彩化等 |
imageconvolution(resource $im, matrix, div, offset) | 3x3 卷積矩陣(自訂濾鏡) |
imagerotate(resource $im, angle, bgdcolor, ignoretransparent) | 旋轉圖片 |
imageflip(resource $im, mode) | 翻轉:水平/垂直/雙向 |
imagecrop(resource $im, rect) | 裁切 |
imagecropauto(resource $im, mode, threshold, color) | 自動裁切 |
imagescale(resource $im, new_width, new_height, mode) | 縮放(回傳新圖片資源) |
imageaffine(resource $im, matrix, rect) | 仿射變換 |
imagelayereffect(resource $im, effect) | 圖層混合模式 |
imagealphablending(resource $im, bool) | 開啟/關閉 Alpha 混合 |
imagesavealpha(resource $im, bool) | 儲存時保留 Alpha 通道 |
imageantialias(resource $im, bool) | 開啟抗鋸齒(線條/多邊形) |
imagegammacorrect(resource $im, input_gamma, output_gamma) | Gamma 校正 |
imageinterlace(resource $im, bool) | 隔行掃描(漸進式 JPEG) |
十、PS 字型(舊功能,少用)
imagepsloadfont, imagepstext, imagepsbbox, imagepsencodefont, imagepsextendfont, imagepsslantfont, imagepsfreefont —— PostScript Type 1 字型支援,PHP 7.0+ 已移除。
十一、格式轉換工具函式
| 函式 | 說明 |
jpeg2wbmp(jpeg, wbmp, dest_height, dest_width, threshold) | JPEG 轉 WBMP |
png2wbmp(png, wbmp, dest_height, dest_width, threshold) | PNG 轉 WBMP |
iptcembed(iptcdata, jpeg_file, spool) | 嵌入 IPTC 資料到 JPEG |
iptcparse(iptcblock) | 解析 IPTC 區塊 |
常見坑點與最佳實踐
- 記憶體洩漏: 所有
imagecreate* 必須配對 imagedestroy()。
- PNG 透明: 輸出前
imagealphablending($im, false); imagesavealpha($im, true);。
- 中文亂碼: 必須用
imagettftext + TTF 字型檔,內建字型不支援中文。
- 大圖處理:
ini_set('memory_limit', '512M'),或改用 ImageMagick 串流處理。
- 錯誤處理: GD 函式失敗回傳
false,需檢查並 error_log。
- 安全性: 使用者上傳圖片處理前,先
getimagesize 驗證類型,避免惡意檔案。
GD vs ImageMagick 選擇指南