處理大量圖片縮略圖生成是常見需求(如商品圖、用戶頭像)。本文提供一個功能完整的 image 類別,支援本地/遠程圖片來源、自動建立目錄、MD5 亂碼命名避免衝突、等比縮放/裁切、品質控制、GIF/JPG/PNG 多格式處理,並內建快取機制避免重複處理。
mkdirs() 遞歸建立儲存目錄。savefile() 相容 file_put_contents 與舊版 fwrite。getsuffix()、checksuffix() 過濾允許格式。Mini():支援寬高指定、品質參數、遠程圖片自動下載、比例計算裁切、imagecopyresampled 高品質重採樣。reNames() 產生 {寬}_{高}_{MD5片段}.{副檔名} 格式,含尺寸資訊利於辨識。$over=0 時直接返回路徑,避免重複運算。class image {
public $src, $newsrc, $allowtype = [".gif", ".jpg", ".png", ".jpeg"];
public $regif = 0, $keep = 0, $over = 0;
public $dir, $newdir;
public function __construct($olddir = null, $newdir = null) {
$this->dir = $olddir ?? "./images/temp";
$this->newdir = $newdir ?? "./images/s";
}
public function Mini($src, $w, $h, $q = 80) {
$this->src = $src; $this->w = $w; $this->h = $h;
if (strrchr($src, ".") == ".gif" && $this->regif == 0) return $this->src;
$newsrc = $this->keep == 0 ? $this->reNames($src)
: $this->newdir . strrchr(str_replace("\\", "/", $src), "/");
if (file_exists($newsrc) && $this->over == 0) return $newsrc;
if (strpos($src, "https://") === 0 && strpos($src, $_SERVER['HTTP_HOST']) === false) {
$src = $this->getimg($src);
}
$arr = getimagesize($src);
[$width, $height, $type] = [$arr[0], $arr[1], $arr[2]];
$im = match($type) {
1 => imagecreatefromgif($src),
2 => imagecreatefromjpeg($src),
3 => imagecreatefrompng($src),
default => return 0,
};
// 計算裁切區域:保持目標比例,從源圖中心裁切
$nim = imagecreatetruecolor($w, $h);
$k1 = round($h / $w, 2);
$k2 = round($height / $width, 2);
if ($k1 < $k2) {
$width_a = $width; $height_a = round($width * $k1);
$sw = 0; $sh = ($height - $height_a) / 2;
} else {
$width_a = $height / $k1; $height_a = $height;
$sw = ($width - $width_a) / 2; $sh = 0;
}
if (function_exists('imagecopyresampled')) {
imagecopyresampled($nim, $im, 0, 0, $sw, $sh, $w, $h, $width_a, $height_a);
} else {
imagecopyresized($nim, $im, 0, 0, $sw, $sh, $w, $h, $width_a, $height_a);
}
if (!is_dir($this->newdir)) mkdir($this->newdir, 0777, true);
$rs = match($type) {
1 => imagegif($nim, $newsrc),
2 => imagejpeg($nim, $newsrc, $q),
3 => imagepng($nim, $newsrc),
default => 0,
};
imagedestroy($im); imagedestroy($nim);
return $newsrc;
}
// 其他輔助方法:getimg(), reNames(), reImg()...
}
// 使用範例
$img = new image();
echo $img->reImg("images/zht.jpg", 75, 75, 80) . "
";
echo $img->reImg("images/m8920.jpg", 75, 75, 80) . "
";
try-catch 包裹、記錄失敗日誌。memory_limit,處理後及時 imagedestroy()。imagecreatefromwebp()、imagewebp() 輸出新一代格式,大幅減小檔案體積。Content-Type、限制檔案大小、禁用 allow_url_fopen 改用 cURL。此類別為批量縮略圖處理提供了堅實基礎,配合現代化儲存服務 (S3、雲存儲) 與 CDN 整合,可構建高效能圖片處理管線。