萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 圖片處理類:多尺寸縮略圖生成與保存

Web 開發中頻繁需要將上傳圖片生成多種尺寸的縮略圖(如列表圖、詳情圖、頭像)。本文提供一個功能完整的 ImageCls 類,封裝了圖片載入、縮放、裁剪、水印、保存、輸出等常用操作,支援 JPEG/PNG/GIF/WebP 格式。

類核心功能

  • 自動識別圖片類型並創建 GD 資源
  • 等比縮放、固定寬高裁剪、智能裁剪(保留中心/面部)
  • 支援多目標尺寸一次性生成
  • 文字/圖片水印(支援透明度、位置、偏移)
  • 質量壓縮、格式轉換、EXIF 方向自動修正
  • 鏈式調用,靈活擴展

簡化版核心代碼結構

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 方向自動修正:讀取 exif_read_data() 的 Orientation 標籤,調用 imagerotate() 修正手機拍攝照片旋轉問題。
  • 記憶體優化:大圖處理前調用 ini_set('memory_limit', '256M'),處理完及時 imagedestroy() 釋放資源。
  • WebP 支援:PHP 5.5+ 內建 imagecreatefromwebp/imagewebp,優化前端加載速度。
  • 錯誤處理:統一拋出異常,上層捕獲記錄日誌並返回友好提示。

擴展建議

  • 集成 Intervention/Image 或 Imagine 等成熟庫,獲得更豐富功能(濾鏡、文字排版、動圖處理)。
  • 異步生成:上傳後推送消息隊列,Worker 進程後台生成縮略圖,提升接口響應速度。
  • CDN 回源:縮略圖按需生成並緩存至 CDN,減少源站存儲與帶寬。

這個圖片類封裝了 GD 庫的常用操作,代碼結構清晰,易於維護擴展,是中小項目快速實現圖片處理需求的實用組件。

copyright © 萬盛學電腦網 all rights reserved