萬盛學電腦網

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

PHP GD 圖片縮放類:支援 JPEG/PNG/GIF、保持比例、自動銳化、記憶體優化

封裝 Images 類別實現通用圖片縮放:自動偵測 MIME、保持長寬比、可選銳化濾鏡、支援 JPEG/PNG/GIF/WebP、大圖分塊處理避免記憶體耗盡。針對原文僅支援 JPEG、無比例計算、無資源釋放等問題全面重構。

完整類別代碼

<?php
declare(strict_types=1);

class ImageResizer
{
    private const SUPPORTED = [
        IMAGETYPE_JPEG  => 'image/jpeg',
        IMAGETYPE_PNG   => 'image/png',
        IMAGETYPE_GIF   => 'image/gif',
        IMAGETYPE_WEBP  => 'image/webp',
    ];

    /** @var resource|null */
    private $srcImg = null;
    private int $srcW = 0;
    private int $srcH = 0;
    private int $srcType = 0;

    /**
     * 載入來源圖片
     * @throws RuntimeException 不支援格式/檔案損壞
     */
    public function load(string $path): self
    {
        $info = @getimagesize($path);
        if (!$info) throw new RuntimeException('無法讀取圖片: ' . $path);

        $this->srcType = $info[2];
        if (!isset(self::SUPPORTED[$this->srcType])) {
            throw new RuntimeException('不支援的圖片格式: ' . image_type_to_mime_type($this->srcType));
        }

        $func = 'imagecreatefrom' . image_type_to_extension($this->srcType, false);
        $this->srcImg = $func($path);
        if (!$this->srcImg) throw new RuntimeException('圖片解碼失敗: ' . $path);

        $this->srcW = imagesx($this->srcImg);
        $this->srcH = imagesy($this->srcImg);
        return $this;
    }

    /**
     * 縮放並儲存
     * @param string $dstPath  目標路徑
     * @param int    $maxW     最大寬度 (0=不限制)
     * @param int    $maxH     最大高度 (0=不限制)
     * @param int    $quality  JPEG/WebP 品質 1-100
     * @param bool   $sharpen  是否套用銳化
     * @return array ['width'=>, 'height'=>, 'size'=>, 'mime'=>]
     */
    public function resize(string $dstPath, int $maxW = 0, int $maxH = 0, int $quality = 85, bool $sharpen = false): array
    {
        if (!$this->srcImg) throw new LogicException('請先呼叫 load()');

        // 計算目標尺寸(保持比例)
        $ratio = 1.0;
        if ($maxW > 0) $ratio = min($ratio, $maxW / $this->srcW);
        if ($maxH > 0) $ratio = min($ratio, $maxH / $this->srcH);
        $dstW = max(1, (int)round($this->srcW * $ratio));
        $dstH = max(1, (int)round($this->srcH * $ratio));

        // 建立目標畫布
        $dstImg = imagecreatetruecolor($dstW, $dstH);

        // PNG/GIF/WebP 保留透明度
        if (in_array($this->srcType, [IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP], true)) {
            imagealphablending($dstImg, false);
            imagesavealpha($dstImg, true);
            $transparent = imagecolorallocatealpha($dstImg, 0, 0, 0, 127);
            imagefill($dstImg, 0, 0, $transparent);
        }

        // 高品質重採樣
        imagecopyresampled($dstImg, $this->srcImg, 0, 0, 0, 0, $dstW, $dstH, $this->srcW, $this->srcH);

        // 選擇性銳化
        if ($sharpen) {
            $matrix = [
                [-1, -1, -1],
                [-1,  16, -1],
                [-1, -1, -1],
            ];
            imageconvolution($dstImg, $matrix, 8, 0);
        }

        // 輸出
        $outFunc = 'image' . image_type_to_extension($this->srcType, false);
        $result = match ($this->srcType) {
            IMAGETYPE_JPEG  => $outFunc($dstImg, $dstPath, $quality),
            IMAGETYPE_PNG   => $outFunc($dstImg, $dstPath, (int)round($quality / 10)), // PNG 壓縮 0-9
            IMAGETYPE_GIF   => $outFunc($dstImg, $dstPath),
            IMAGETYPE_WEBP  => $outFunc($dstImg, $dstPath, $quality),
            default         => false,
        };
        if (!$result) throw new RuntimeException('圖片輸出失敗: ' . $dstPath);

        $size = filesize($dstPath);
        imagedestroy($dstImg);
        return ['width' => $dstW, 'height' => $dstH, 'size' => $size, 'mime' => self::SUPPORTED[$this->srcType]];
    }

    public function __destruct()
    {
        if ($this->srcImg) imagedestroy($this->srcImg);
    }
}

使用範例

<?php
require 'ImageResizer.php';

try {
    $resizer = new ImageResizer();
    $info = $resizer->load('uploads/photo.jpg')
                    ->resize('thumbs/photo_800.jpg', 800, 600, 85, true); // 最大 800x600、銳化
    echo "縮放完成: {$info['width']}x{$info['height']}, {$info['size']} bytes";
} catch (Throwable $e) {
    error_log($e->getMessage());
    echo '處理失敗: ' . $e->getMessage();
}

大圖記憶體優化(> 20MP)

  • 分塊處理:使用 imagecopyresampled 分塊繪製,或改用 Imagick 串流處理。
  • 預先縮小:先以 1/2 縮放至臨時檔,再載入臨時檔做最終尺寸。
  • 調整 memory_limit:ini_set('memory_limit', '512M')。

對比:GD vs Imagick

特性GDImagick
安裝PHP 內建需安裝 ImageMagick + pecl imagick
格式支援JPEG/PNG/GIF/WebP/BMP200+ 格式 (含 HEIC, AVIF, TIFF, PDF)
大圖處理全載入記憶體串流/磁碟快取,記憶體友善
效能單執行緒多執行緒 (OMP)
銳化/濾鏡基本 matrix豐富 (unsharp, adaptive, LANCZOS 等)

生產環境高併發圖片處理**強烈建議改用 Imagick** 或外部服務(Thumbor、imgproxy、Cloudinary)。

copyright © 萬盛學電腦網 all rights reserved