基於 GD2 擴展的圖片縮略圖生成是 PHP 經典剛需。本文封裝一個 make_thumb() 函數:自動檢測源圖格式(JPEG/PNG/GIF/WebP)、等比計算目標高度、真彩色畫布繪製、輸出質量可配、目錄自建、錯誤異常化。
function make_thumb(string $src, string $dest, int $desiredWidth, int $quality = 85): bool {
// 1. 檢測源文件
if (!is_file($src) || !is_readable($src)) throw new InvalidArgumentException("源文件不可讀: $src");
$info = getimagesize($src);
if (!$info) throw new RuntimeException("非有效圖片或格式不支援: $src");
[$srcW, $srcH, $type] = $info;
// 2. 計算目標高度(等比)
$desiredHeight = (int)round($srcH * ($desiredWidth / $srcW));
// 3. 創建源圖資源
$createFrom = match ($type) {
IMAGETYPE_JPEG => 'imagecreatefromjpeg',
IMAGETYPE_PNG => 'imagecreatefrompng',
IMAGETYPE_GIF => 'imagecreatefromgif',
IMAGETYPE_WEBP => 'imagecreatefromwebp',
default => throw new RuntimeException("不支援的圖片類型: $type"),
};
$source = $createFrom($src);
if (!$source) throw new RuntimeException("GD 無法解碼圖片: $src");
// 4. 創建真彩色目標畫布
$thumb = imagecreatetruecolor($desiredWidth, $desiredHeight);
// 5. 保持透明度(PNG/GIF/WebP)
if (in_array($type, [IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP], true)) {
imagealphablending($thumb, false);
imagesavealpha($thumb, true);
$transparent = imagecolorallocatealpha($thumb, 0, 0, 0, 127);
imagefill($thumb, 0, 0, $transparent);
}
// 6. 高質量重採樣縮放
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $desiredWidth, $desiredHeight, $srcW, $srcH);
// 7. 確保目標目錄存在
$destDir = dirname($dest);
if (!is_dir($destDir)) mkdir($destDir, 0755, true);
// 8. 輸出(根據目標副檔名或源類型決定格式)
$destType = $type;
$destExt = strtolower(pathinfo($dest, PATHINFO_EXTENSION));
$saveFunc = match ($destType) {
IMAGETYPE_JPEG => fn() => imagejpeg($thumb, $dest, $quality),
IMAGETYPE_PNG => fn() => imagepng($thumb, $dest, (int)round($quality / 10 * 9)), // PNG 壓縮級 0-9
IMAGETYPE_GIF => fn() => imagegif($thumb, $dest),
IMAGETYPE_WEBP => fn() => imagewebp($thumb, $dest, $quality),
default => throw new RuntimeException("目標格式不支援輸出"),
};
$ok = $saveFunc();
// 9. 釋放資源
imagedestroy($source);
imagedestroy($thumb);
return $ok;
}
// 生成 300px 寬縮略圖,質量 80
make_thumb('uploads/photo.jpg', 'thumbs/photo_300.jpg', 300, 80);
// 批量處理上傳目錄
foreach (glob('uploads/*.{jpg,png,gif,webp}', GLOB_BRACE) as $file) {
$name = basename($file);
make_thumb($file, "thumbs/{$name}", 400);
make_thumb($file, "thumbs/small_{$name}", 150);
}
| 維度 | GD (內建) | Imagick (擴展) |
|---|---|---|
| 安裝部署 | PHP 核心編譯參數 --with-gd,幾乎全環境可用 | 需安裝 ImageMagick 庫 + pecl imagick,版本兼容性較麻煩 |
| 格式支援 | JPEG/PNG/GIF/WebP/BMP/XBM | 200+ 格式(HEIC、AVIF、TIFF、PSD、RAW...) |
| 性能 | 純 C 實現,中等 | 多線程、SIMD 優化,大圖快 2-5 倍 |
| 高級功能 | 基礎繪圖、濾鏡、文字 | ✓ 圖層、蒙版、向量、色彩空間轉換、EXIF 保留、PDF 渲染 |
| 記憶體管理 | PHP 進程內,受 memory_limit 限制 | ImageMagick 獨立進程/共享內存,可配置 MAGICK_MEMORY_LIMIT |
| 推薦場景 | 簡單縮略圖、水印、驗證碼、低併發 | 高併發、複雜圖像處理、多格式、色彩管理關鍵場景 |
memory_limit 或改用 Imagick 流式處理。Orientation 手動 imagerotate 或用 Imagick autoOrientImage()。imagealphablending(false) + imagesavealpha(true) + 填充透明色。現代專案建議:簡單縮略圖用 GD(零依賴)、複雜處理/高併發用 Imagick、極致性能用 libvips + php-vips(輕量、流式、多核並行)。