專案中常需「上傳大圖 → 自動產生指定尺寸縮圖」的單一功能,不想引入完整類別時,一個獨立函式最適合。本文提供 bigtosmallimg(),支援 GIF/JPEG/PNG、等比縮放、自動輸出同格式,四個參數即可完成。
function bigtosmallimg($file, $path, $w=120, $h=90) {
// $file : 原圖檔名 (含副檔名)
// $path : 原圖目錄路徑 (結尾含 /)
// $w : 目標最大寬度
// $h : 目標最大高度
}
function bigtosmallimg($file, $path, $w=120, $h=90) {
$img = $path . $file;
$imgarr = getimagesize($img);
if (!$imgarr) return false;
$sw = $imgarr[0]; $sh = $imgarr[1]; $stype = $imgarr[2];
// 等比縮放:取較小縮放比
if ($sw/$sh > $w/$h) {
$mw = $w;
$mh = (int)($sh * ($w/$sw));
} else {
$mw = (int)($sw * ($h/$sh));
$mh = $h;
}
// 建立來源資源
switch ($stype) {
case 1: $srcf = imagecreatefromgif($img); break;
case 2: $srcf = imagecreatefromjpeg($img); break;
case 3: $srcf = imagecreatefrompng($img); break;
default: return false;
}
// 真彩畫布 + 高畫質重採樣
$desf = imagecreatetruecolor($mw, $mh);
imagecopyresampled($desf, $srcf, 0,0,0,0, $mw,$mh, $sw,$sh);
// 輸出檔名:s_ 原檔名
$sm_name = $path . "s_" . $file;
switch ($stype) {
case 1: imagegif($desf, $sm_name); break;
case 2: imagejpeg($desf, $sm_name); break;
case 3: imagepng($desf, $sm_name); break;
}
imagedestroy($desf);
imagedestroy($srcf);
return $sm_name; // 回傳縮圖路徑
}
// 上傳完成後
$original = 'photo.jpg';
$dir = 'uploads/';
// 產生 200x200 內的等比縮圖
$thumb = bigtosmallimg($original, $dir, 200, 200);
if ($thumb) {
echo "縮圖已產生: $thumb"; // uploads/s_photo.jpg
} else {
echo "縮圖失敗:格式不支援或檔案不存在";
}
$sw/$sh (原圖比例) 與 $w/$h (目標比例),決定以寬或高為基準,確保縮圖完整包含原圖內容,不會裁切。imagecreate + imagecopyresized。$stype 輸出同格式,避免 GIF 動畫變靜態、PNG 透明度變黑底。imagedestroy() 避免批次處理時記憶體洩漏。| 需求 | 修改方式 |
|---|---|
| 裁切填滿 (Cover 模式) | 計算較大縮放比,再 imagecopyresampled 時加負座標裁切 |
| 指定輸出格式 (統一 WebP) | 移除 switch 輸出,統一 imagewebp($desf, $path.'s_'.basename($file,'.').'.webp', 85) |
| 支援 WebP/HEIC 輸入 | switch 新增 case 17: imagecreatefromwebp (需 GD 2.3+) |
| 回傳 GD 資源而非存檔 | 移除存檔邏輯,直接 return $desf; 讓呼叫端決定 |
| 品質參數 | 新增 $quality=90 參數傳給 imagejpeg/png/webp |
foreach (glob('uploads/*.{jpg,png,gif}', GLOB_BRACE) as $file) {
$name = basename($file);
$thumb = bigtosmallimg($name, 'uploads/', 300, 300);
echo $thumb ? "✓ $name\n" : "✗ $name\n";
}
use Intervention\Image\ImageManagerStatic as Image;
Image::make('uploads/photo.jpg')
->fit(200, 200, function($c) { $c->aspectRatio(); })
->save('uploads/s_photo.jpg');
bigtosmallimg() 以 30 行程式碼解決「等比縮圖 + 格式保留 + 高畫質」的核心需求,零依賴、易複製貼上,適合輕量專案或舊系統維護。新專案建議直接採用 Intervention Image,獲得更豐富的操作鏈與單元測試支援。