電商商品圖、文章縮圖、使用者頭像需**統一尺寸** (如 160×120px) 但**不想變形**。解法:**等比縮放至目標框內 + 白邊填充置中**。
<?php
/**
* 產生固定尺寸縮略圖 (等比縮放 + 白邊填充置中)
*
* @param string $srcPath 來源圖路徑/URL
* @param int $targetW 目標寬度
* @param int $targetH 目標高度
* @param string $outputPath 輸出路徑 (null 直接輸出瀏覽器)
* @param int $quality JPEG 品質 0-100
* @return bool
*/
function createThumbWithPadding(string $srcPath, int $targetW, int $targetH, ?string $outputPath = null, int $quality = 90): bool
{
// 1. 讀取來源圖 (支援 URL、本地、data://)
$srcData = file_get_contents($srcPath);
if ($srcData === false) return false;
$src = imagecreatefromstring($srcData);
if (!$src) return false;
$srcW = imagesx($src);
$srcH = imagesy($src);
// 2. 計算等比縮放後尺寸 (寬高皆不超過目標框)
$ratioSrc = $srcW / $srcH;
$ratioTarget = $targetW / $targetH;
if ($ratioSrc >= $ratioTarget) {
// 來源較寬 → 以寬度為基準
$tmpW = $targetW;
$tmpH = (int)round($targetW / $ratioSrc);
} else {
// 來源較高 → 以高度為基準
$tmpH = $targetH;
$tmpW = (int)round($targetH * $ratioSrc);
}
// 3. 建立中繼縮略圖 (高品質重採樣)
$tmp = imagecreatetruecolor($tmpW, $tmpH);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tmpW, $tmpH, $srcW, $srcH);
// 4. 建立最終畫布 (白底)
$dst = imagecreatetruecolor($targetW, $targetH);
$white = imagecolorallocate($dst, 255, 255, 255);
imagefill($dst, 0, 0, $white);
// 5. 置中貼上
$x = (int)(($targetW - $tmpW) / 2);
$y = (int)(($targetH - $tmpH) / 2);
imagecopy($dst, $tmp, $x, $y, 0, 0, $tmpW, $tmpH);
// 6. 輸出
$success = false;
if ($outputPath) {
$success = imagejpeg($dst, $outputPath, $quality);
} else {
header('Content-Type: image/jpeg');
$success = imagejpeg($dst, null, $quality);
}
// 7. 釋放資源
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($dst);
return $success;
}
// 使用範例
createThumbWithPadding('uploads/original.jpg', 160, 120, 'thumbs/thumb_160x120.jpg');
| 函式 | 用途 |
|---|---|
| `imagecreatefromstring()` | 從二進位字串建立圖片資源 (自動偵測 JPEG/PNG/GIF/WebP) |
| `imagesx()` / `imagesy()` | 取得圖片寬/高 |
| `imagecreatetruecolor()` | 建立真彩色畫布 (24-bit RGB) |
| `imagecopyresampled()` | **高品質** 縮放/複製 (雙立方插值),優於 `imagecopyresized` |
| `imagecolorallocate()` | 分配顏色索引 |
| `imagefill()` | 填滿畫布 |
| `imagecopy()` | 像素級複製 (無縮放) |
| `imagejpeg()` | 輸出 JPEG (檔案/瀏覽器) |
// Intervention Image (Laravel 常用)
use Intervention\Image\ImageManagerStatic as Image;
Image::make('original.jpg')
->fit(160, 120, function ($constraint) {
$constraint->upsize(); // 允許放大
})
->save('thumb.jpg', 90);
// spatie/image (更輕量、PHP 8+)
use Spatie\Image\Image;
Image::load('original.jpg')
->width(160)
->height(120)
->fit(Spati\Image\Manipulations\FitMode::CONTAIN) // 等比含蓋 = 白邊
->save('thumb.jpg');
核心邏輯:**計算比例 → 等比縮放至目標框內 → 建立白底畫布 → 置中貼上**。掌握 `imagecopyresampled` 高品質縮放與座標計算,即可處理所有固定尺寸縮圖需求。生產環境建議引入 Intervention Image 等封裝庫,簡化代碼、自動處理資源釋放、支援更多格式。