通用 PHP 圖片縮放函數,支援按最大寬高等比縮放、優先使用 imagecopyresampled 高質量重採樣、自動處理 JPEG/PNG/GIF 格式、保持透明度、輸出到檔案。適合頭像上傳、縮略圖生成、圖片壓縮場景。
$maxWidth) || ($maxHeight && $srcH > $maxHeight)) {
// 計算縮放比例
$widthRatio = ($maxWidth && $srcW > $maxWidth) ? $maxWidth / $srcW : 1;
$heightRatio = ($maxHeight && $srcH > $maxHeight) ? $maxHeight / $srcH : 1;
$ratio = min($widthRatio, $heightRatio); // 取較小比例,確保不超限
$dstW = (int)($srcW * $ratio);
$dstH = (int)($srcH * $ratio);
// 建立目標圖片 (真彩色支援透明度)
if (function_exists('imagecreatetruecolor')) {
$dst = imagecreatetruecolor($dstW, $dstH);
// 保持 PNG/GIF 透明度
if ($filetype === '.png' || $filetype === '.gif') {
imagealphablending($dst, false);
imagesavealpha($dst, true);
$transparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
imagefill($dst, 0, 0, $transparent);
}
imagecopyresampled($dst, $im, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);
} else {
// 老版本 GD 降級
$dst = imagecreate($dstW, $dstH);
imagecopyresized($dst, $im, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);
}
// 輸出
switch ($filetype) {
case '.jpg': case '.jpeg': imagejpeg($dst, $name . $filetype, 90); break;
case '.png': imagepng($dst, $name . $filetype, 6); break;
case '.gif': imagegif($dst, $name . $filetype); break;
}
imagedestroy($dst);
} else {
// 原圖直接輸出
switch ($filetype) {
case '.jpg': case '.jpeg': imagejpeg($im, $name . $filetype, 90); break;
case '.png': imagepng($im, $name . $filetype, 6); break;
case '.gif': imagegif($im, $name . $filetype); break;
}
}
imagedestroy($im);
}
// 使用範例
$source = 'upload/photo.jpg';
$im = imagecreatefromjpeg($source);
resizeImage($im, 800, 600, 'thumb/photo', '.jpg'); // 最大 800x600
?>
| 特性 | 實作方式 |
|---|---|
| 等比縮放 | min($widthRatio, $heightRatio) 取較小比例,確保寬高均不超限 |
| 高質量重採樣 | imagecopyresampled 雙立方插值,邊緣平滑 (優於 imagecopyresized) |
| 真彩色支援 | imagecreatetruecolor 24位色彩 + Alpha 通道 |
| 透明度保持 | PNG/GIF: imagesavealpha + imagealphablending(false) |
| 品質控制 | JPEG: 90% 品質;PNG: 壓縮級別 6 (平衡大小/速度) |
| 記憶體釋放 | imagedestroy() 釋放源/目標資源 |
extension=gd 統一支援 JPEG/PNG/GIF/WebP# 安裝依賴
yum install libpng-devel libjpeg-devel freetype-devel
# PHP 編譯參數
./configure --with-gd \
--with-jpeg-dir \
--with-png-dir \
--with-freetype-dir \
--enable-gd-native-ttf
imagecreatefromwebp、imagewebp (PHP 5.5+)$mode 參數 (fit/fill/cover) 控制縮放策略