在 PHP 開發中,圖片縮略圖生成是常見需求。本文提供一個基於 GD 庫的完整類別,支援 JPG、GIF、PNG 三種主流格式,並包含錯誤處理與比例縮放邏輯,可直接整合到專案中使用。
該類別封裝了從檢測 GD 環境、讀取原圖資訊、計算目標尺寸、重新採樣到輸出檔案的完整流程。使用方式極簡單:
<?php
$newImage = new ImageResize();
$newImage->resize("source.jpg", "thumb.jpg", 1000, 1000);
echo $newImage->GetLastError();
_checkenv()啟動時自動檢查 gd_info 函數是否存在,確保伺服器已安裝並啟用 GD 擴展。
_create()根據 getimagesize() 回傳的類型代碼(1=GIF, 2=JPG, 3=PNG),呼叫對應的 imagecreatefrom* 函數建立圖片資源。
_dstsize()依原圖寬高比與目標框寬高比,等比縮放,確保縮略圖不變形。邏輯為:若原圖較扁,以高度為基準計算寬度;否則以寬度為基準計算高度。
_resize()imagecreatetruecolor,並填充透明背景(imagecolorallocatealpha)。imagecopyresampled 高質量重新採樣。imagejpeg、imagepng、imagegif 輸出,相容不同格式需求。類別內部維護 $error 陣列,提供 GetLastError() 與 GetAllError() 兩種獲取方式,方便除錯與日誌記錄。
<?php
class ImageResize {
private $localimage;
private $remoteimage;
private $localinfo;
private $error = [];
public function resize($localimg, $remoteimg, $x, $y) {
if (!$this->_checkenv()) return false;
$this->localimage = $localimg;
$this->remoteimage = $remoteimg;
$this->localinfo = getimagesize($this->localimage);
return $this->_resize($x, $y);
}
private function _checkenv() {
if (!function_exists('gd_info')) {
$this->error[] = "當前環境不支援 GD 圖像處理,請先安裝 GD 庫並開啟 PHP 相關擴展";
return false;
}
return true;
}
private function _resize($x, $y) {
if (!$this->localinfo) {
$this->error[] = "本地圖像文件不存在";
return false;
}
$im = @$this->_create($this->localinfo[2]);
if (!$im) {
$this->error[] = "當前 GD 庫不支援圖像類型:{$this->localinfo['mime']}";
return false;
}
$dstsize = $this->_dstsize($x, $y);
$dstim = @imagecreatetruecolor($dstsize["width"], $dstsize["height"]);
$whitecolor = @imagecolorallocatealpha($dstim, 0, 0, 0, 127);
imagefill($dstim, 0, 0, $whitecolor);
$re = @imagecopyresampled($dstim, $im, 0, 0, 0, 0, $dstsize["width"], $dstsize["height"], $this->localinfo[0], $this->localinfo[1]);
if (!$re) {
$this->error[] = "圖像重新採樣失敗";
return false;
}
// 依序嘗試三種格式輸出
if (!imagejpeg($dstim, $this->remoteimage)
&& !imagepng($dstim, $this->remoteimage)
&& !imagegif($dstim, $this->remoteimage)) {
$this->error[] = "保存縮略圖到 {$this->remoteimage} 失敗,請檢查 GD 環境及目錄寫入權限。";
return false;
}
$this->error[] = "success";
return true;
}
private function _create($code) {
$src = $this->localimage;
switch ($code) {
case 1: return imagecreatefromgif($src);
case 2: return imagecreatefromjpeg($src);
case 3: return imagecreatefrompng($src);
default: return false;
}
}
private function _dstsize($x, $y) {
list($srcwidth, $srcheight) = $this->localinfo;
if (($srcwidth / $srcheight) < ($x / $y)) {
$x = floor($y * $srcwidth / $srcheight);
} else {
$y = floor($x * $srcheight / $srcwidth);
}
return ["width" => $x, "height" => $y];
}
public function GetLastError() { return array_pop($this->error); }
public function GetAllError() { return $this->error; }
}
將上述代碼存為 ImageResize.class.php 即可在專案中直接引入使用。若需調整輸出品質,可在 imagejpeg 呼叫時加入第三參數(0-100)。