產生固定尺寸縮圖時,直接縮放會導致變形,單純裁切可能切掉主體。本文提供智慧裁切縮放函式:根據原圖與目標長寬比,自動決定「先縮放再置中裁切」或「先裁切再縮放」,確保主體完整、無變形、無黑邊,支援主流圖片格式。
$srcRatio = $srcW / $srcH, $dstRatio = $dstW / $dstH<?php
/**
* 智慧裁切縮放:保持比例、置中裁切、無變形
*
* @param string $srcPath 來源圖片路徑
* @param string $dstPath 目標儲存路徑
* @param int $dstWidth 目標寬度
* @param int $dstHeight 目標高度
* @param int $quality 輸出品質 1-100 (JPEG/WebP)
* @return bool 成功與否
*/
function smartCropResize(string $srcPath, string $dstPath, int $dstWidth, int $dstHeight, int $quality = 90): bool
{
if (!file_exists($srcPath)) {
trigger_error("來源檔案不存在: $srcPath", E_USER_WARNING);
return false;
}
if ($dstWidth <= 0 || $dstHeight <= 0) {
trigger_error('目標寬高必須大於 0', E_USER_WARNING);
return false;
}
// 1. 偵測類型並建立資源
$type = exif_imagetype($srcPath);
$createMap = [
IMAGETYPE_JPEG => 'imagecreatefromjpeg',
IMAGETYPE_PNG => 'imagecreatefrompng',
IMAGETYPE_GIF => 'imagecreatefromgif',
IMAGETYPE_WEBP => 'imagecreatefromwebp',
];
if (!isset($createMap[$type])) {
trigger_error('不支援的格式,僅支援 JPEG/PNG/GIF/WebP', E_USER_WARNING);
return false;
}
$srcImg = $createMap[$type]($srcPath);
if (!$srcImg) return false;
$srcW = imagesx($srcImg);
$srcH = imagesy($srcImg);
// 2. 計算中間畫布尺寸
$srcRatio = $srcW / $srcH;
$dstRatio = $dstWidth / $dstHeight;
if ($srcRatio > $dstRatio) {
// 原圖較寬 → 以高為基準
$interW = (int)round($dstHeight * $srcRatio);
$interH = $dstHeight;
} else {
// 原圖較高或等比 → 以寬為基準
$interW = $dstWidth;
$interH = (int)round($dstWidth / $srcRatio);
}
// 3. 建立中間畫布並高品質縮放
$interImg = imagecreatetruecolor($interW, $interH);
// 保留透明度
if (in_array($type, [IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP], true)) {
imagealphablending($interImg, false);
imagesavealpha($interImg, true);
$transparent = imagecolorallocatealpha($interImg, 0, 0, 0, 127);
imagefill($interImg, 0, 0, $transparent);
}
imagecopyresampled($interImg, $srcImg, 0, 0, 0, 0, $interW, $interH, $srcW, $srcH);
// 4. 置中裁切至目標尺寸
$dstImg = imagecreatetruecolor($dstWidth, $dstHeight);
if (in_array($type, [IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP], true)) {
imagealphablending($dstImg, false);
imagesavealpha($dstImg, true);
$transparent = imagecolorallocatealpha($dstImg, 0, 0, 0, 127);
imagefill($dstImg, 0, 0, $transparent);
}
$srcX = ($interW - $dstWidth) / 2;
$srcY = ($interH - $dstHeight) / 2;
imagecopy($dstImg, $interImg, 0, 0, $srcX, $srcY, $dstWidth, $dstHeight);
// 5. 輸出
$outputMap = [
IMAGETYPE_JPEG => fn($img, $p) => imagejpeg($img, $p, $quality),
IMAGETYPE_PNG => fn($img, $p) => imagepng($img, $p, (int)round($quality / 10)), // 0-9
IMAGETYPE_GIF => fn($img, $p) => imagegif($img, $p),
IMAGETYPE_WEBP => fn($img, $p) => imagewebp($img, $p, $quality),
];
$success = $outputMap[$type]($dstImg, $dstPath);
// 6. 釋放資源
imagedestroy($srcImg);
imagedestroy($interImg);
imagedestroy($dstImg);
return $success;
}
<?php
require_once 'smartCropResize.php';
// 產生 400x300 縮圖
smartCropResize('uploads/photo.jpg', 'thumbs/photo_400x300.jpg', 400, 300, 85);
// 批次處理:產生多種尺寸
$sizes = [
'thumb' => [150, 150],
'medium' => [400, 300],
'large' => [800, 600],
];
foreach (glob('uploads/*.{jpg,jpeg,png,gif,webp}', GLOB_BRACE) as $file) {
$base = pathinfo($file, PATHINFO_FILENAME);
foreach ($sizes as $prefix => [$w, $h]) {
smartCropResize($file, "thumbs/{$base}_{$prefix}.jpg", $w, $h, 85);
}
}
$outputMap = [
IMAGETYPE_JPEG => fn($img, $p) => imagewebp($img, $p, $quality),
IMAGETYPE_PNG => fn($img, $p) => imagewebp($img, $p, $quality),
IMAGETYPE_GIF => fn($img, $p) => imagewebp($img, $p, $quality),
IMAGETYPE_WEBP => fn($img, $p) => imagewebp($img, $p, $quality),
];
// 並將 $dstPath 副檔名改為 .webp
| 問題 | 原因 | 解決 |
|---|---|---|
| PNG/GIF 透明背景變黑 | 未啟用 alpha blending + savealpha | 建立畫布後呼叫 imagealphablending($img, false); imagesavealpha($img, true); 並填充透明色 |
| imagecreatefromwebp 不存在 | PHP 編譯未加入 --with-webp 或版本 < 5.5 | 升級 PHP 或安裝 libwebp-devel 重新編譯 |
| 大圖處理記憶體不足 | GD 解碼需大量記憶體 | 調大 memory_limit、改用 ImageMagick (imagick 擴展) |
| 縮圖模糊 | 使用 imagecopyresized 而非 resampled | 務必用 imagecopyresampled 雙三次插值 |
md5($srcPath . $dstWidth . $dstHeight . $quality) 避免重複生成imagick 擴展效能更高、格式支援更全、指令列 convert 更靈活智慧裁切縮放的核心是比例比較 → 基準縮放 → 置中裁切。封裝為可重用函式並妥善處理透明度、記憶體釋放、多格式輸出,即可滿足多數 Web 專案需求。若流量大、圖片多,建議升級至 ImageMagick 或雲端服務,獲得更佳效能與功能。