Web 開發中頻繁需要將上傳圖片生成多種尺寸的縮略圖(如列表圖、詳情圖、頭像)。本文提供一個功能完整的 ImageCls 類,封裝了圖片載入、縮放、裁剪、水印、保存、輸出等常用操作,支援 JPEG/PNG/GIF/WebP 格式。
class ImageCls {
private $srcImg; // 源圖資源
private $srcInfo; // [width, height, type, mime]
private $dstImg; // 目標圖資源
public function __construct($srcPath) {
// 根據 mime 類型創建資源
$this->srcInfo = getimagesize($srcPath);
switch ($this->srcInfo[2]) {
case IMAGETYPE_JPEG: $this->srcImg = imagecreatefromjpeg($srcPath); break;
case IMAGETYPE_PNG: $this->srcImg = imagecreatefrompng($srcPath); break;
case IMAGETYPE_GIF: $this->srcImg = imagecreatefromgif($srcPath); break;
case IMAGETYPE_WEBP: $this->srcImg = imagecreatefromwebp($srcPath); break;
default: throw new Exception("Unsupported image type");
}
// 修正 EXIF 方向
$this->autoRotate();
}
// 等比縮放
public function resize($maxW, $maxH) {
$ratio = min($maxW/$this->srcInfo[0], $maxH/$this->srcInfo[1]);
$newW = (int)($this->srcInfo[0] * $ratio);
$newH = (int)($this->srcInfo[1] * $ratio);
$this->dstImg = imagescale($this->srcImg, $newW, $newH, IMG_BICUBIC);
return $this;
}
// 固定尺寸裁剪(居中)
public function crop($w, $h, $x = null, $y = null) {
$x = $x === null ? ($this->getWidth() - $w) / 2 : $x;
$y = $y === null ? ($this->getHeight() - $h) / 2 : $y;
$this->dstImg = imagecrop($this->srcImg, ['x'=>$x,'y'=>$y,'width'=>$w,'height'=>$h]);
return $this;
}
// 添加水印
public function watermark($waterPath, $position = 'bottom-right', $opacity = 50, $offsetX = 10, $offsetY = 10) { ... }
// 保存文件
public function save($dstPath, $quality = 85) {
$type = $this->getTypeFromPath($dstPath);
switch ($type) {
case IMAGETYPE_JPEG: imagejpeg($this->dstImg ?: $this->srcImg, $dstPath, $quality); break;
case IMAGETYPE_PNG: imagepng($this->dstImg ?: $this->srcImg, $dstPath, 9); break;
case IMAGETYPE_GIF: imagegif($this->dstImg ?: $this->srcImg, $dstPath); break;
case IMAGETYPE_WEBP: imagewebp($this->dstImg ?: $this->srcImg, $dstPath, $quality); break;
}
return $this;
}
// 輸出到瀏覽器
public function output($type = IMAGETYPE_JPEG, $quality = 85) { ... }
// 獲取當前資源寬高
public function getWidth() { return imagesx($this->dstImg ?: $this->srcImg); }
public function getHeight() { return imagesy($this->dstImg ?: $this->srcImg); }
// 鏈式調用需返回 $this
}
// 生成三種尺寸縮略圖
$img = new ImageCls('upload/photo.jpg');
$img->resize(800, 600)->save('thumb/photo_800.jpg');
$img->crop(300, 300)->save('thumb/photo_300_square.jpg');
$img->resize(100, 100)->watermark('logo.png')->save('thumb/photo_100_wm.jpg');
exif_read_data() 的 Orientation 標籤,調用 imagerotate() 修正手機拍攝照片旋轉問題。ini_set('memory_limit', '256M'),處理完及時 imagedestroy() 釋放資源。imagecreatefromwebp/imagewebp,優化前端加載速度。Intervention/Image 或 Imagine 等成熟庫,獲得更豐富功能(濾鏡、文字排版、動圖處理)。這個圖片類封裝了 GD 庫的常用操作,代碼結構清晰,易於維護擴展,是中小項目快速實現圖片處理需求的實用組件。