函數功能
- 自動識別源圖格式 (GIF/JPEG/PNG)。
- 按指定寬高等比或強制縮放。
- 輸出為 JPEG 文件或直接瀏覽器輸出。
完整代碼
<?php
/**
* 生成縮略圖
* @param string $srcFile 源文件路徑
* @param string $dstFile 目標文件路徑 (輸出到瀏覽器時傳 null)
* @param int $dstW 目標寬度
* @param int $dstH 目標高度
* @param int $quality JPEG 品質 0-100 (默認 85)
* @return bool 成功返回 true
*/
function makeThumb(string $srcFile, ?string $dstFile, int $dstW, int $dstH, int $quality = 85): bool {
if (!is_file($srcFile)) return false;
$info = getimagesize($srcFile);
if (!$info) return false;
$srcMime = $info['mime'];
switch ($srcMime) {
case 'image/gif': $src = imagecreatefromgif($srcFile); break;
case 'image/jpeg': $src = imagecreatefromjpeg($srcFile); break;
case 'image/png': $src = imagecreatefrompng($srcFile); break;
default: return false;
}
if (!$src) return false;
$srcW = imagesx($src);
$srcH = imagesy($src);
// 建立真彩色畫布 (支援透明度)
$dst = imagecreatetruecolor($dstW, $dstH);
// 保持透明通道 (GIF/PNG)
if ($srcMime === 'image/gif' || $srcMime === 'image/png') {
imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
imagealphablending($dst, false);
imagesavealpha($dst, true);
}
// 重採樣縮放 (質量優於 ImageCopyResized)
imagecopyresampled($dst, $src, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);
// 輸出
if ($dstFile) {
$result = imagejpeg($dst, $dstFile, $quality);
} else {
header('Content-Type: image/jpeg');
$result = imagejpeg($dst, null, $quality);
}
imagedestroy($src);
imagedestroy($dst);
return $result;
}
// 使用示例
makeThumb('uploads/photo.png', 'thumbs/photo_thumb.jpg', 200, 150);
// 直接輸出到瀏覽器
// makeThumb('uploads/photo.jpg', null, 300, 200);
?>
進階:等比例縮放 (保持長寬比)
function calcDstSize(int $srcW, int $srcH, int $maxW, int $maxH): array {
$ratio = min($maxW / $srcW, $maxH / $srcH);
return [ (int)($srcW * $ratio), (int)($srcH * $ratio) ];
}
// 用法
[$dstW, $dstH] = calcDstSize($srcW, $srcH, 200, 150);
makeThumb($src, $dst, $dstW, $dstH);