萬盛學電腦網

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

PHP 圖片等比縮放利器:SimpleImage 類完整使用指南與實戰範例

前言

圖片處理是 Web 開發常見需求:縮圖、水印、格式轉換、等比縮放。SimpleImage 是一個輕量、零依賴(僅需 GD 擴充)、單檔案的 PHP 類別,專注於「簡單好用」,適合快速整合至專案中。

安裝與需求

  • PHP 5.3+ / 7.x / 8.x
  • GD 擴充(extension=gd)
  • 下載 SimpleImage.php 放入專案(官方來源)

核心功能速覽

方法用途回傳值
load($filename)載入圖片(JPG/PNG/GIF)$this (鏈式呼叫)
save($filename, $type=IMAGETYPE_JPEG, $quality=75, $perms=null)儲存至檔案bool
output($type=IMAGETYPE_JPEG)直接輸出至瀏覽器void
resizeToWidth($width)指定寬度,等比縮放$this
resizeToHeight($height)指定高度,等比縮放$this
resize($width, $height)指定寬高(可能變形)$this
scale($percent)按百分比縮放(50 = 50%)$this
getWidth() / getHeight()取得目前圖片尺寸int

常用場景範例

1. 產生固定寬度縮圖(電商商品列表)

<?php
require 'SimpleImage.php';

$image = new SimpleImage();
$image->load('uploads/product_original.jpg')
      ->resizeToWidth(300)           // 寬 300px,高度自動等比
      ->save('uploads/product_thumb_300.jpg', IMAGETYPE_JPEG, 85);

2. 固定高度縮圖(橫幅廣告)

<?php
$image = new SimpleImage();
$image->load('banner_source.png')
      ->resizeToHeight(200)
      ->save('banner_200h.png', IMAGETYPE_PNG);

3. 百分比縮放(保留原始比例快速預覽)

<?php
$image = new SimpleImage();
$image->load('photo.jpg')
      ->scale(50)  // 縮小至 50%
      ->save('photo_half.jpg');

4. 直接輸出至瀏覽器(動態縮圖 API)

<?php
// thumbnail.php?src=photo.jpg&w=150
require 'SimpleImage.php';

$src = $_GET['src'] ?? 'default.jpg';
$width = (int)($_GET['w'] ?? 150);

// 安全驗證:防止路徑遍歷
$src = basename($src);
$allowed = ['jpg', 'jpeg', 'png', 'gif'];
$ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) $src = 'default.jpg';

$image = new SimpleImage();
if ($image->load("uploads/$src")) {
    header('Content-Type: image/jpeg');
    $image->resizeToWidth($width)->output();
} else {
    http_response_code(404);
}

5. 進階:下載遠端圖片 → 縮放 → 儲存(含清理暫存)

<?php
require 'SimpleImage.php';

function downloadAndResize(string $url, int $targetWidth, string $saveDir): ?string
{
    // 1. 下載
    $ctx = stream_context_create([
        'http' => [
            'timeout' => 10,
            'header' => 'User-Agent: Mozilla/5.0',
            'follow_location' => 1,
            'max_redirects' => 3,
        ],
        'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
    ]);
    $content = @file_get_contents($url, false, $ctx);
    if (!$content) return null;

    // 2. 寫入暫存檔
    $tmpDir = sys_get_temp_dir() . '/simpleimage_' . date('Ymd');
    @mkdir($tmpDir, 0755, true);
    $tmpFile = tempnam($tmpDir, 'src_');
    file_put_contents($tmpFile, $content);

    // 3. 處理
    $image = new SimpleImage();
    if (!$image->load($tmpFile)) {
        @unlink($tmpFile);
        return null;
    }
    $image->resizeToWidth($targetWidth);

    // 4. 儲存結果
    @mkdir($saveDir, 0755, true);
    $outFile = $saveDir . '/' . uniqid('img_') . '.jpg';
    $image->save($outFile, IMAGETYPE_JPEG, 85);

    // 5. 清理暫存
    @unlink($tmpFile);

    return $outFile;
}

// 使用
$out = downloadAndResize(
    'https://example.com/large-photo.jpg',
    800,
    __DIR__ . '/public/thumbs'
);
echo $out ? "完成: $out" : "失敗";

SimpleImage 類別原始碼精簡版(核心邏輯)

<?php
class SimpleImage {
    private $image;
    private $imageType;

    public function load($filename) {
        $info = getimagesize($filename);
        if (!$info) return false;
        $this->imageType = $info[2];
        switch ($this->imageType) {
            case IMAGETYPE_JPEG: $this->image = @imagecreatefromjpeg($filename); break;
            case IMAGETYPE_GIF:  $this->image = @imagecreatefromgif($filename);  break;
            case IMAGETYPE_PNG:  $this->image = @imagecreatefrompng($filename);  break;
            default: return false;
        }
        return $this;
    }

    public function save($filename, $type = IMAGETYPE_JPEG, $quality = 75, $perms = null) {
        $result = false;
        switch ($type) {
            case IMAGETYPE_JPEG: $result = imagejpeg($this->image, $filename, $quality); break;
            case IMAGETYPE_GIF:  $result = imagegif($this->image, $filename); break;
            case IMAGETYPE_PNG:  $result = imagepng($this->image, $filename); break;
        }
        if ($result && $perms !== null) chmod($filename, $perms);
        return $result;
    }

    public function output($type = IMAGETYPE_JPEG) {
        header('Content-Type: ' . image_type_to_mime_type($type));
        switch ($type) {
            case IMAGETYPE_JPEG: imagejpeg($this->image); break;
            case IMAGETYPE_GIF:  imagegif($this->image); break;
            case IMAGETYPE_PNG:  imagepng($this->image); break;
        }
    }

    public function getWidth()  { return imagesx($this->image); }
    public function getHeight() { return imagesy($this->image); }

    public function resizeToWidth($width) {
        $ratio = $width / $this->getWidth();
        $height = $this->getHeight() * $ratio;
        return $this->resize($width, $height);
    }

    public function resizeToHeight($height) {
        $ratio = $height / $this->getHeight();
        $width = $this->getWidth() * $ratio;
        return $this->resize($width, $height);
    }

    public function scale($percent) {
        $width = $this->getWidth() * $percent / 100;
        $height = $this->getHeight() * $percent / 100;
        return $this->resize($width, $height);
    }

    public function resize($width, $height) {
        $new = imagecreatetruecolor($width, $height);
        // 保留 PNG/GIF 透明度
        if ($this->imageType == IMAGETYPE_PNG || $this->imageType == IMAGETYPE_GIF) {
            imagealphablending($new, false);
            imagesavealpha($new, true);
            $transparent = imagecolorallocatealpha($new, 255, 255, 255, 127);
            imagefill($new, 0, 0, $transparent);
        }
        imagecopyresampled($new, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
        $this->image = $new;
        return $this;
    }
}

效能與品質調校建議

  • 品質參數: JPEG 75-85 平衡檔案大小與視覺品質;PNG 無損但檔案較大
  • 避免多次重壓: 原始圖 → 目標尺寸一次到位,勿多次 save() 疊加損失
  • 大圖處理: 記憶體限制 ini_set('memory_limit', '256M');極大圖考慮 ImageMagick (imagick 擴充)
  • WebP 輸出: PHP 7.0+ 支援 imagewebp(),可擴充 save() 支援 IMAGETYPE_WEBP

常見問題排查

問題原因解決
輸出圖片空白/破圖load() 失敗、路徑錯誤、GD 不支援格式檢查 load() 回傳值、file_exists、getimagesize 回傳
PNG/GIF 透明變黑底未啟用 alpha blending / savealpharesize() 中加入 alphablending + savealpha 邏輯(上方原始碼已含)
縮放後模糊原圖過小被放大、品質參數過低僅縮小不放大、提高 quality、考慮銳化濾鏡
記憶體耗盡大尺寸圖片(如 5000x5000)解碼需大量記憶體調高 memory_limit、分塊處理、改用 ImageMagick

總結

SimpleImage 以 單一檔案、零依賴、API 直覺 三大優勢,成為 PHP 專案快速整合圖片縮放的首選。掌握 load → resizeToWidth/Height/scale → save/output 鏈式操作,即可滿足 90% 的縮圖需求。搭配暫存檔清理、安全驗證、品質調校,即可在生產環境穩定運行。若需更強功能(EXIF 保留、ICC 色彩空間、AVIF/WebP、向量圖),請升級至 Intervention Image 或直接使用 ImageMagick。

copyright © 萬盛學電腦網 all rights reserved