萬盛學電腦網

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

PHP 通用圖片處理類:縮放、裁剪、水印、濾鏡一站式解決方案

前言

Web 應用常需處理使用者上傳圖片:生成多尺寸縮圖、添加品牌水印、裁剪比例、套用濾鏡效果。本文整理一個基於 GD 擴展的完整圖片處理類,支援鏈式呼叫、歷史記錄回溯、多格式輸出,適合整合至 CMS、電商、社群平台。

核心功能清單

功能方法說明
縮放resize($w, $h, $mode)等比縮放、裁剪填充、拉伸填充三種模式
裁剪crop($x, $y, $w, $h)座標裁剪、智慧裁剪(焦點居中)
水印watermark($source, $position, $opacity)圖片/文字水印、九宮格定位、透明度控制
旋轉rotate($angle, $bgColor)任意角度旋轉、背景填充色
翻轉flip($mode)水平/垂直/雙向翻轉
銳化sharpen($amount)非銳化遮罩 (USM) 演算法
濾鏡filter($type, $args)灰階、負片、色調分離、高斯模糊、自定義卷積核
相框frame($width, $color, $style)實線、虛線、圖片邊框
透明度opacity($level)整體透明度調整
歷史記錄undo()/redo()/saveSnapshot()支援多步驟回溯,自動生成版本檔名

類別架構設計

<?php
class ImageProcessor {
    private $sourcePath;
    private $image;           // GD 資源
    private $width, $height;
    private $mimeType;
    private $history = [];    // 快照堆疊
    private $historyIndex = -1;
    private $tempDir;

    public function __construct(string $sourcePath) {
        $this->sourcePath = $sourcePath;
        $this->tempDir = sys_get_temp_dir() . '/imgproc_' . uniqid();
        mkdir($this->tempDir, 0755, true);
        $this->load($sourcePath);
        $this->saveSnapshot();
    }

    // 靜態工廠方法
    public static function fromString(string $binary, string $mimeType): self {
        $tmp = tempnam(sys_get_temp_dir(), 'img_');
        file_put_contents($tmp, $binary);
        $instance = new self($tmp);
        $instance->mimeType = $mimeType;
        return $instance;
    }

    private function load(string $path): void {
        $info = getimagesize($path);
        $this->width = $info[0];
        $this->height = $info[1];
        $this->mimeType = $info['mime'];

        $createFunc = match($this->mimeType) {
            'image/jpeg' => 'imagecreatefromjpeg',
            'image/png'  => 'imagecreatefrompng',
            'image/gif'  => 'imagecreatefromgif',
            'image/webp' => 'imagecreatefromwebp',
            default => throw new InvalidArgumentException("不支援格式:{$this->mimeType}")
        };
        $this->image = $createFunc($path);
        if (!$this->image) throw new RuntimeException("圖片載入失敗:$path");

        // 保持透明度
        if (in_array($this->mimeType, ['image/png', 'image/gif', 'image/webp'])) {
            imagealphablending($this->image, false);
            imagesavealpha($this->image, true);
        }
    }

    private function saveSnapshot(): void {
        // 截斷 redo 堆疊
        $this->history = array_slice($this->history, 0, $this->historyIndex + 1);
        // 儲存當前狀態到暫存檔
        $snapshotPath = $this->tempDir . '/step_' . (++$this->historyIndex) . '.dat';
        $this->saveToFile($snapshotPath);
        $this->history[] = $snapshotPath;
    }

    private function saveToFile(string $path): void {
        $func = match($this->mimeType) {
            'image/jpeg' => fn() => imagejpeg($this->image, $path, 95),
            'image/png'  => fn() => imagepng($this->image, $path, 9),
            'image/gif'  => fn() => imagegif($this->image, $path),
            'image/webp' => fn() => imagewebp($this->image, $path, 90),
        };
        $func();
    }

    public function undo(): ?self {
        if ($this->historyIndex <= 0) return null;
        $this->historyIndex--;
        $this->load($this->history[$this->historyIndex]);
        return $this;
    }

    public function redo(): ?self {
        if ($this->historyIndex >= count($this->history) - 1) return null;
        $this->historyIndex++;
        $this->load($this->history[$this->historyIndex]);
        return $this;
    }

    // --- 核心操作方法(回傳 $this 支援鏈式呼叫) ---

    public function resize(int $width, int $height, string $mode = 'fit'): self {
        $newImage = imagecreatetruecolor($width, $height);
        if (in_array($this->mimeType, ['image/png', 'image/gif', 'image/webp'])) {
            imagealphablending($newImage, false);
            imagesavealpha($newImage, true);
        }

        $srcW = $this->width;
        $srcH = $this->height;
        $srcX = $srcY = 0;
        $dstW = $width;
        $dstH = $height;

        switch ($mode) {
            case 'fit':      // 等比縮放,完整顯示(可能留白)
                $ratio = min($width / $srcW, $height / $srcH);
                $dstW = (int)($srcW * $ratio);
                $dstH = (int)($srcH * $ratio);
                $srcX = ($width - $dstW) / 2;
                $srcY = ($height - $dstH) / 2;
                break;
            case 'fill':     // 等比縮放並裁剪填滿
                $ratio = max($width / $srcW, $height / $srcH);
                $srcW = (int)($width / $ratio);
                $srcH = (int)($height / $ratio);
                $srcX = ($this->width - $srcW) / 2;
                $srcY = ($this->height - $srcH) / 2;
                break;
            case 'stretch':  // 強制拉伸
            default:
                break;
        }

        imagecopyresampled($newImage, $this->image, $srcX, $srcY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
        imagedestroy($this->image);
        $this->image = $newImage;
        $this->width = $width;
        $this->height = $height;
        $this->saveSnapshot();
        return $this;
    }

    public function crop(int $x, int $y, int $width, int $height): self {
        $newImage = imagecreatetruecolor($width, $height);
        if (in_array($this->mimeType, ['image/png', 'image/gif', 'image/webp'])) {
            imagealphablending($newImage, false);
            imagesavealpha($newImage, true);
        }
        imagecopy($newImage, $this->image, 0, 0, $x, $y, $width, $height);
        imagedestroy($this->image);
        $this->image = $newImage;
        $this->width = $width;
        $this->height = $height;
        $this->saveSnapshot();
        return $this;
    }

    public function watermark(string $markPath, string $position = 'br', int $opacity = 50): self {
        $mark = imagecreatefrompng($markPath); // 建議水印用 PNG 透明背景
        $markW = imagesx($mark);
        $markH = imagesy($mark);

        $positions = [
            'tl' => [0, 0], 'tc' => [($this->width-$markW)/2, 0], 'tr' => [$this->width-$markW, 0],
            'ml' => [0, ($this->height-$markH)/2], 'mc' => [($this->width-$markW)/2, ($this->height-$markH)/2],
            'mr' => [$this->width-$markW, ($this->height-$markH)/2],
            'bl' => [0, $this->height-$markH], 'bc' => [($this->width-$markW)/2, $this->height-$markH],
            'br' => [$this->width-$markW, $this->height-$markH],
        ];
        [$destX, $destY] = $positions[$position] ?? $positions['br'];

        imagecopymerge($this->image, $mark, $destX, $destY, 0, 0, $markW, $markH, $opacity);
        imagedestroy($mark);
        $this->saveSnapshot();
        return $this;
    }

    public function rotate(float $angle, array $bgColor = [255,255,255]): self {
        $bg = imagecolorallocatealpha($this->image, ...$bgColor, 127);
        $rotated = imagerotate($this->image, -$angle, $bg); // GD 角度方向相反
        imagedestroy($this->image);
        $this->image = $rotated;
        $this->width = imagesx($rotated);
        $this->height = imagesy($rotated);
        $this->saveSnapshot();
        return $this;
    }

    public function filter(int $filterType, ...$args): self {
        imagefilter($this->image, $filterType, ...$args);
        $this->saveSnapshot();
        return $this;
    }

    // 輸出
    public function save(string $destPath, int $quality = 90): bool {
        $dir = dirname($destPath);
        if (!is_dir($dir)) mkdir($dir, 0755, true);
        $func = match($this->mimeType) {
            'image/jpeg' => fn() => imagejpeg($this->image, $destPath, $quality),
            'image/png'  => fn() => imagepng($this->image, $destPath, (int)($quality/10)),
            'image/gif'  => fn() => imagegif($this->image, $destPath),
            'image/webp' => fn() => imagewebp($this->image, $destPath, $quality),
        };
        return $func();
    }

    public function output(int $quality = 90): void {
        header('Content-Type: ' . $this->mimeType);
        $func = match($this->mimeType) {
            'image/jpeg' => fn() => imagejpeg($this->image, null, $quality),
            'image/png'  => fn() => imagepng($this->image, null, (int)($quality/10)),
            'image/gif'  => fn() => imagegif($this->image),
            'image/webp' => fn() => imagewebp($this->image, null, $quality),
        };
        $func();
    }

    public function __destruct() {
        if ($this->image) imagedestroy($this->image);
        // 清理暫存目錄
        if (is_dir($this->tempDir)) {
            array_map('unlink', glob($this->tempDir . '/*'));
            rmdir($this->tempDir);
        }
    }
}

使用範例

$processor = new ImageProcessor('uploads/photo.jpg')
    ->resize(800, 600, 'fit')
    ->filter(IMG_FILTER_GRAYSCALE)
    ->watermark('assets/logo.png', 'br', 30)
    ->save('output/photo_processed.jpg');

// 產生多尺寸縮圖
$sizes = ['thumb' => [150,150], 'medium' => [400,300], 'large' => [800,600]];
foreach ($sizes as $name => [$w, $h]) {
    (new ImageProcessor('uploads/photo.jpg'))
        ->resize($w, $h, 'fill')
        ->save("output/photo_{$name}.jpg");
}

效能與擴充建議

  • 大圖處理:GD 受限於記憶體,超過 4000x4000 像素建議改用 Imagick 擴展(多執行緒、流式處理)。
  • 批次處理:搭配 Queue Worker(Laravel Queue、Symfony Messenger)非同步處理。
  • 智慧裁剪:整合 Intervention Image 的 fit() 焦點裁剪,或使用 OpenCV 人臉偵測定位裁剪區域。
  • WebP/AVIF 輸出:現代瀏覽器支援度高,可大幅減少流量,GD 8.1+ 原生支援 imagewebp/imageavif。

總結

此類別封裝了 GD 擴展的核心功能,提供直觀的鏈式 API 與歷史回溯機制,滿足大多數 Web 圖片處理需求。若專案涉及大量高解析度圖片或複雜向量操作,建議遷移至 Imagick 或雲端圖片處理服務(Imgix、Cloudinary)。

copyright © 萬盛學電腦網 all rights reserved