萬盛學電腦網

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

PHP GD2 生成圖片縮略圖類:支援裁切、等比縮放、多格式

前置條件

服務器需安裝並啟用 GD2 擴展(extension=gd),支援 JPEG、PNG、GIF、WebP 等格式。

縮略圖類完整實現

<?php
/**
 * 圖片縮略圖生成類
 * 支援:等比縮放、裁切模式、多格式輸出、品質控制
 */
class ThumbnailGenerator
{
    private $srcPath;
    private $dstPath;
    private $maxWidth;
    private $maxHeight;
    private $cropMode;      // true=裁切填滿,false=等比縮放
    private $quality;       // JPEG 輸出品質 0-100
    private $imageResource;
    private $srcInfo;       // [width, height, type, mime]

    public function __construct(
        string $srcPath,
        int $maxWidth,
        int $maxHeight,
        bool $cropMode = false,
        string $dstPath = '',
        int $quality = 85
    ) {
        $this->srcPath = $srcPath;
        $this->maxWidth = $maxWidth;
        $this->maxHeight = $maxHeight;
        $this->cropMode = $cropMode;
        $this->quality = $quality;
        $this->dstPath = $dstPath ?: $this->buildDstPath($srcPath);
        
        $this->initImage();
        $this->generate();
        $this->cleanup();
    }

    /** 初始化圖片資源 */
    private function initImage(): void {
        if (!file_exists($this->srcPath)) {
            throw new RuntimeException("源圖片不存在:{$this->srcPath}");
        }
        
        $this->srcInfo = getimagesize($this->srcPath);
        if ($this->srcInfo === false) {
            throw new RuntimeException("無法識別圖片格式:{$this->srcPath}");
        }
        
        [$srcW, $srcH, $type] = $this->srcInfo;
        $createFunc = match ($type) {
            IMAGETYPE_JPEG => 'imagecreatefromjpeg',
            IMAGETYPE_PNG  => 'imagecreatefrompng',
            IMAGETYPE_GIF  => 'imagecreatefromgif',
            IMAGETYPE_WEBP => 'imagecreatefromwebp',
            default => throw new RuntimeException("不支援的圖片類型:{$type}"),
        };
        
        $this->imageResource = $createFunc($this->srcPath);
        if ($this->imageResource === false) {
            throw new RuntimeException("圖片資源創建失敗");
        }
        
        // PNG/GIF 保持透明通道
        if (in_array($type, [IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP])) {
            imagealphablending($this->imageResource, false);
            imagesavealpha($this->imageResource, true);
        }
    }

    /** 生成縮略圖核心邏輯 */
    private function generate(): void {
        [$srcW, $srcH] = $this->srcInfo;
        $srcRatio = $srcW / $srcH;
        $dstRatio = $this->maxWidth / $this->maxHeight;

        if ($this->cropMode) {
            // 裁切模式:填滿目標尺寸,居中裁切
            if ($srcRatio >= $dstRatio) {
                // 寬度較寬,按高度縮放再裁寬
                $newH = $this->maxHeight;
                $newW = $srcRatio * $newH;
                $srcX = ($newW - $this->maxWidth) / 2;
                $srcY = 0;
                $srcW = $this->maxWidth;
                $srcH = $newH;
            } else {
                // 高度較高,按寬度縮放再裁高
                $newW = $this->maxWidth;
                $newH = $newW / $srcRatio;
                $srcX = 0;
                $srcY = ($newH - $this->maxHeight) / 2;
                $srcW = $newW;
                $srcH = $this->maxHeight;
            }
            $dstW = $this->maxWidth;
            $dstH = $this->maxHeight;
        } else {
            // 等比縮放:完整顯示,留白
            if ($srcRatio >= $dstRatio) {
                $dstW = $this->maxWidth;
                $dstH = $dstW / $srcRatio;
            } else {
                $dstH = $this->maxHeight;
                $dstW = $dstH * $srcRatio;
            }
            $srcX = $srcY = 0;
        }

        // 創建真彩色目標畫布
        $dstImg = imagecreatetruecolor($dstW, $dstH);
        
        // 透明背景處理
        if (in_array($this->srcInfo[2], [IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP])) {
            $transparent = imagecolorallocatealpha($dstImg, 0, 0, 0, 127);
            imagefill($dstImg, 0, 0, $transparent);
            imagealphablending($dstImg, true);
            imagesavealpha($dstImg, true);
        }

        // 高質量重採樣
        imagecopyresampled(
            $dstImg, $this->imageResource,
            0, 0, $srcX, $srcY,
            $dstW, $dstH,
            $srcW, $srcH
        );

        // 輸出保存
        $this->saveImage($dstImg);
        imagedestroy($dstImg);
    }

    /** 根據副檔名決定輸出格式 */
    private function saveImage($dstImg): void {
        $ext = strtolower(pathinfo($this->dstPath, PATHINFO_EXTENSION));
        switch ($ext) {
            case 'jpg':
            case 'jpeg':
                imagejpeg($dstImg, $this->dstPath, $this->quality);
                break;
            case 'png':
                imagepng($dstImg, $this->dstPath, 9); // 壓縮級別 0-9
                break;
            case 'gif':
                imagegif($dstImg, $this->dstPath);
                break;
            case 'webp':
                imagewebp($dstImg, $this->dstPath, $this->quality);
                break;
            default:
                // 默認 JPEG
                $this->dstPath = preg_replace('/\.[^.]+$/', '.jpg', $this->dstPath);
                imagejpeg($dstImg, $this->dstPath, $this->quality);
        }
    }

    /** 自動生成目標路徑 */
    private function buildDstPath(string $src): string {
        $info = pathinfo($src);
        $dir = $info['dirname'] ?? '.';
        $name = $info['filename'];
        $ext = $info['extension'] ?? 'jpg';
        return "{$dir}/{$name}_thumb_{$this->maxWidth}x{$this->maxHeight}.{$ext}";
    }

    /** 釋放資源 */
    private function cleanup(): void {
        if ($this->imageResource) {
            imagedestroy($this->imageResource);
        }
    }

    /** 靜態工廠方法,鏈式調用更優雅 */
    public static function make(string $src, int $w, int $h, bool $crop = false, string $dst = '', int $q = 85): self {
        return new self($src, $w, $h, $crop, $dst, $q);
    }
}

// 使用示例
// 等比縮放,長邊不超過 200px
ThumbnailGenerator::make('uploads/photo.jpg', 200, 200);

// 裁切模式,強制 200x200 正方形
ThumbnailGenerator::make('uploads/photo.jpg', 200, 200, true, 'thumbs/photo_square.jpg');

// 自定義品質、輸出 WebP
ThumbnailGenerator::make('uploads/photo.png', 400, 300, false, 'thumbs/photo.webp', 90);
?>

關鍵技術點解析

1. imagecopyresampled vs imagecopyresized

imagecopyresampled() 使用雙三次插值算法,輸出質量遠優於 imagecopyresized() 的最近鄰插值,**生產環境務必使用前者**。

2. 透明通道保持

// PNG/GIF/WebP 必須設置
imagealphablending($img, false);
imagesavealpha($img, true);

否則透明區域會變黑或變白。

3. 內存管理

  • 大圖處理前調大 memory_limit(如 256M)
  • 及時 imagedestroy() 釋放 GD 資源
  • 超大圖(>5000px)建議分塊處理或用 ImageMagick

4. 錯誤處理最佳實踐

try {
    ThumbnailGenerator::make($src, 300, 300);
    echo '縮略圖生成成功';
} catch (RuntimeException $e) {
    error_log($e->getMessage());
    // 回退方案:複製原圖或使用佔位圖
}

性能對比與選型建議

方案優點缺點適用場景
GD2 (本類)無額外依賴、PHP 內置、部署簡單大圖內存佔用高、功能較基礎 中小型項目、常規縮略圖
ImageMagick (imagick)功能強大、處理大圖高效、支援更多格式需安裝擴展、部署較複雜 高質量需求、批量處理、複雜圖像操作
Intervention/ImageAPI 優雅、鏈式調用、封裝 GD/Imagick引入 Composer 依賴 現代 Laravel/Symfony 專案首選

總結

本類封裝了 GD2 縮略圖生成的完整流程,支援裁切/等比兩種模式、多格式輸出、透明通道保持、品質控制。代碼採用現代 PHP 風格(類型聲明、match 表達式、異常處理),可直接投入生產使用。對於高併發、大圖片場景,建議異步隊列處理並考慮遷移至 ImageMagick。

copyright © 萬盛學電腦網 all rights reserved