| 分類 | 代表函數 |
| 資訊獲取 | gd_info(), getimagesize(), getimagesizefromstring(), image_type_to_extension(), image_type_to_mime_type() |
| 畫布建立 | imagecreatetruecolor(), imagecreate(), imagecreatefromjpeg/png/gif/webp/bmp/string() |
| 輸出輸出 | imagejpeg/png/gif/webp/wbmp/bmp(), image2wbmp() |
| 顏色管理 | imagecolorallocate(), imagecolorallocatealpha(), imagecolorat(), imagecolorclosest(), imagecolorclosestalpha(), imagecolorclosesthwb() |
| 幾何繪製 | imagesetpixel(), imageline(), imagerectangle(), imagepolygon(), imageellipse(), imagearc(), imagefilledrectangle(), imagefilledpolygon(), imagefilledellipse(), imagefill(), imagefilltoborder() |
| 文字繪製 | imagestring(), imagestringup(), imagettftext(), imagettfbbox(), imagechar(), imagecharup() |
| 圖片複製合成 | imagecopy(), imagecopyresized(), imagecopyresampled(), imagecopymerge(), imagecopymergegray() |
| 幾何變換 | imagerotate(), imageflip(), imagecrop(), imagecropauto(), imageaffine(), imageaffinematrixget(), imageaffinematrixconcat() |
| 特效濾鏡 | imagefilter(), imageconvolution(), imageantialias(), imagealphablending(), imagesavealpha() |
| 尺寸資訊 | imagesx(), imagesy() |
| 資源釋放 | imagedestroy() |
實戰範例集
1. 產生驗證碼圖片
<?php
session_start();
$width = 120; $height = 40;
$image = imagecreatetruecolor($width, $height);
// 背景
$bg = imagecolorallocate($image, 230, 230, 230);
imagefilledrectangle($image, 0, 0, $width, $height, $bg);
// 雜訊線條
for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($image, rand(100,200), rand(100,200), rand(100,200));
imageline($image, rand(0,$width), rand(0,$height), rand(0,$width), rand(0,$height), $color);
}
// 驗證碼文字
$code = '';
for ($i = 0; $i < 4; $i++) $code .= chr(rand(65,90)); // A-Z
$_SESSION['captcha'] = $code;
$fontSize = 5;
$x = 15;
foreach (str_split($code) as $char) {
$color = imagecolorallocate($image, rand(0,100), rand(0,100), rand(0,100));
imagestring($image, $fontSize, $x, 10, $char, $color);
$x += 22;
}
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
2. 圖片縮圖 (保持比例、高品質)
function createThumbnail($srcPath, $destPath, $maxWidth, $maxHeight, $quality = 85) {
list($srcW, $srcH, $type) = getimagesize($srcPath);
if (!$srcW || !$srcH) return false;
$ratio = min($maxWidth/$srcW, $maxHeight/$srcH);
if ($ratio >= 1) return copy($srcPath, $destPath); // 無需縮小
$dstW = (int)($srcW * $ratio);
$dstH = (int)($srcH * $ratio);
$srcImg = match($type) {
IMAGETYPE_JPEG => imagecreatefromjpeg($srcPath),
IMAGETYPE_PNG => imagecreatefrompng($srcPath),
IMAGETYPE_GIF => imagecreatefromgif($srcPath),
IMAGETYPE_WEBP => imagecreatefromwebp($srcPath),
default => null
};
if (!$srcImg) return false;
$dstImg = imagecreatetruecolor($dstW, $dstH);
// 保持透明度 (PNG/GIF)
if ($type === IMAGETYPE_PNG || $type === IMAGETYPE_GIF) {
imagealphablending($dstImg, false);
imagesavealpha($dstImg, true);
$transparent = imagecolorallocatealpha($dstImg, 255, 255, 255, 127);
imagefilledrectangle($dstImg, 0, 0, $dstW, $dstH, $transparent);
}
imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);
$success = match($type) {
IMAGETYPE_JPEG => imagejpeg($dstImg, $destPath, $quality),
IMAGETYPE_PNG => imagepng($dstImg, $destPath, 9),
IMAGETYPE_GIF => imagegif($dstImg, $destPath),
IMAGETYPE_WEBP => imagewebp($dstImg, $destPath, $quality),
default => false
};
imagedestroy($srcImg);
imagedestroy($dstImg);
return $success;
}
3. 添加文字水印
function addTextWatermark($srcPath, $destPath, $text, $fontFile, $fontSize = 20, $color = [255,255,255], $alpha = 50, $position = 'bottom-right', $margin = 10) {
list($w, $h, $type) = getimagesize($srcPath);
$src = imagecreatefromjpeg($srcPath); // 簡化:假設 JPEG
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $w, $h);
$textColor = imagecolorallocatealpha($dst, $color[0], $color[1], $color[2], $alpha);
$box = imagettfbbox($fontSize, 0, $fontFile, $text);
$textW = $box[2] - $box[0];
$textH = $box[1] - $box[7];
switch ($position) {
case 'top-left': $x = $margin; $y = $margin + $textH; break;
case 'top-right': $x = $w - $textW - $margin; $y = $margin + $textH; break;
case 'bottom-left': $x = $margin; $y = $h - $margin; break;
case 'bottom-right': $x = $w - $textW - $margin; $y = $h - $margin; break;
case 'center': $x = ($w - $textW)/2; $y = ($h + $textH)/2; break;
}
imagettftext($dst, $fontSize, 0, $x, $y, $textColor, $fontFile, $text);
imagejpeg($dst, $destPath, 90);
imagedestroy($src); imagedestroy($dst);
}
4. 繪製簡單統計圖表 (長條圖)
function drawBarChart($data, $width = 600, $height = 400) {
$img = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($img, 255, 255, 255);
$gray = imagecolorallocate($img, 200, 200, 200);
$blue = imagecolorallocate($img, 66, 133, 244);
$dark = imagecolorallocate($img, 51, 51, 51);
imagefilledrectangle($img, 0, 0, $width, $height, $white);
$maxVal = max($data);
$barCount = count($data);
$barWidth = 40;
$gap = ($width - $barCount * $barWidth) / ($barCount + 1);
$scale = ($height - 80) / $maxVal;
$x = $gap;
foreach ($data as $label => $value) {
$barH = (int)($value * $scale);
$y = $height - 50 - $barH;
imagefilledrectangle($img, $x, $y, $x + $barWidth, $height - 50, $blue);
imagestring($img, 3, $x + 5, $height - 40, $label, $dark);
imagestring($img, 3, $x + 5, $y - 20, $value, $dark);
$x += $barWidth + $gap;
}
// 座標軸
imageline($img, 30, 30, 30, $height - 50, $dark);
imageline($img, 30, $height - 50, $width - 30, $height - 50, $dark);
header('Content-Type: image/png');
imagepng($img);
imagedestroy($img);
}
// 使用
drawBarChart(['Jan'=>120, 'Feb'=>150, 'Mar'=>180, 'Apr'=>200]);
常見問題與最佳實務
| 問題 | 解決方案 |
| 記憶體耗盡 | 大圖處理前調大 memory_limit,處理完立即 imagedestroy() |
| 透明背景變黑 | 啟用 imagealphablending($img, false); imagesavealpha($img, true); |
| 中文字體亂碼 | 使用 imagettftext() 載入 .ttf 字體檔,確保檔案路徑正確 |
| JPEG 品質/大小平衡 | imagejpeg($img, null, 75-85) 通常最佳 |
| 並發處理效能 | 考慮 ImageMagick (imagick 擴展) 或外部服務 |
GD vs ImageMagick 選擇指南
| 維度 | GD | ImageMagick |
| 功能豐富度 | 基礎繪圖、文字、縮放 | 200+ 格式、進階特效、向量圖、色彩管理 |
| 效能 | 簡單操作較快 | 複雜操作優化更好 |
| 記憶體管理 | PHP 進程內 | 外部進程/共享記憶體 |
| 部署複雜度 | PHP 內建,零依賴 | 需安裝 ImageMagick + imagick 擴展 |
| 適用場景 | 驗證碼、縮圖、簡單水印、圖表 | 專業圖片處理、批次轉檔、色彩校正、PDF/向量 |
總結
GD 庫是 PHP 內建圖形處理的基石,掌握畫布建立、顏色管理、幾何繪製、文字渲染、圖片合成、輸出輸出等核心流程,即可實現驗證碼、縮圖、水印、圖表等常見需求。對於高階圖像處理,建議評估 ImageMagick 或雲端圖片處理服務 (Imgix, Cloudinary, AWS Lambda@Edge)。
- 上一篇文章: PHP RESTful API 實戰教學:從零建立符合 REST 架構的 Web 服務
- 下一篇文章: PHP 時區完整列表:支援的時區識別符與最佳實務設定指南
Copyright ©
程式碼之家 All Rights Reserved