萬盛學電腦網

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

PHP 簡易縮略圖類:等比例縮放、裁剪填充與多格式支援

類別設計

<?php
class Thumbnailer
{
    private $srcPath;
    private $srcImage;
    private $srcInfo; // [width, height, type, mime]

    public function __construct(string $srcPath)
    {
        if (!is_file($srcPath)) throw new InvalidArgumentException("Source not found: $srcPath");
        $this->srcPath = $srcPath;
        $this->srcInfo = getimagesize($srcPath);
        if (!$this->srcInfo) throw new RuntimeException('Invalid image file');
        $this->loadSource();
    }

    private function loadSource(): void
    {
        $type = $this->srcInfo[2];
        $func = match ($type) {
            IMAGETYPE_JPEG => 'imagecreatefromjpeg',
            IMAGETYPE_PNG  => 'imagecreatefrompng',
            IMAGETYPE_GIF  => 'imagecreatefromgif',
            IMAGETYPE_WEBP => 'imagecreatefromwebp',
            default => throw new RuntimeException('Unsupported image type'),
        };
        $this->srcImage = $func($this->srcPath);
        if (!$this->srcImage) throw new RuntimeException('Failed to load image');
    }

    /** 等比例縮放,長邊限制在 $maxW x $maxH 內 */
    public function resize(int $maxW, int $maxH): self
    {
        [$sw, $sh] = $this->srcInfo;
        $scale = min($maxW / $sw, $maxH / $sh);
        $dw = (int)($sw * $scale);
        $dh = (int)($sh * $scale);
        $this->transform($dw, $dh, 0, 0, $sw, $sh);
        return $this;
    }

    /** 裁剪填充:縮放至覆蓋目標區域,再居中裁剪至 $w x $h */
    public function crop(int $w, int $h): self
    {
        [$sw, $sh] = $this->srcInfo;
        $scale = max($w / $sw, $h / $sh);
        $iw = (int)($sw * $scale);
        $ih = (int)($sh * $scale);
        $sx = (int)(($iw - $w) / 2);
        $sy = (int)(($ih - $h) / 2);
        $this->transform($w, $h, $sx, $sy, $iw, $ih);
        return $this;
    }

    private function transform(int $dw, int $dh, int $sx, int $sy, int $sw, int $sh): void
    {
        $dst = imagecreatetruecolor($dw, $dh);
        // 保留透明度
        if (in_array($this->srcInfo[2], [IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP], true)) {
            imagealphablending($dst, false);
            imagesavealpha($dst, true);
            $transparent = imagecolortransparent($this->srcImage);
            if ($transparent >= 0) {
                $rgb = imagecolorsforindex($this->srcImage, $transparent);
                $newT = imagecolorallocatealpha($dst, $rgb['red'], $rgb['green'], $rgb['blue'], 127);
                imagefill($dst, 0, 0, $newT);
                imagecolortransparent($dst, $newT);
            }
        }
        imagecopyresampled($dst, $this->srcImage, 0, 0, $sx, $sy, $dw, $dh, $sw, $sh);
        imagedestroy($this->srcImage);
        $this->srcImage = $dst;
        $this->srcInfo[0] = $dw;
        $this->srcInfo[1] = $dh;
    }

    public function save(string $destPath, int $quality = 85): bool
    {
        $type = $this->srcInfo[2];
        $func = match ($type) {
            IMAGETYPE_JPEG => fn() => imagejpeg($this->srcImage, $destPath, $quality),
            IMAGETYPE_PNG  => fn() => imagepng($this->srcImage, $destPath, 9),
            IMAGETYPE_GIF  => fn() => imagegif($this->srcImage, $destPath),
            IMAGETYPE_WEBP => fn() => imagewebp($this->srcImage, $destPath, $quality),
            default => throw new RuntimeException('Unsupported output type'),
        };
        $result = $func();
        imagedestroy($this->srcImage);
        return $result;
    }

    public function __destruct()
    {
        if (is_resource($this->srcImage)) imagedestroy($this->srcImage);
    }
}
?>

使用範例

<?php
// 等比縮放 (適合列表圖)
$thumb = new Thumbnailer('uploads/photo.jpg');
$thumb->resize(800, 600)->save('thumbs/photo_800x600.jpg');

// 裁剪填充 (適合頭像、封面)
$avatar = new Thumbnailer('uploads/avatar.png');
$avatar->crop(200, 200)->save('avatars/user_200.webp'); // 輸出 WebP 更小

// 批次處理
foreach (glob('uploads/*.{jpg,png,gif}', GLOB_BRACE) as $file) {
    try {
        (new Thumbnailer($file))->resize(400, 300)->save('thumbs/' . basename($file));
    } catch (Throwable $e) {
        error_log("Thumb failed $file: {$e->getMessage()}");
    }
}
?>

效能與記憶體提示

  • 大圖處理前調大 `memory_limit` (如 `ini_set('memory_limit', '256M')`)
  • 單次處理完畢立即銷毀資源,類別已實現 `__destruct` 保底
  • 超大量批次建議使用 CLI 模式 + `pcntl_fork` 平行處理
copyright © 萬盛學電腦網 all rights reserved