首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 批量生成圖片縮略圖類別:支援遠程抓取、MD5 命名、比例裁切與多格式輸出

     編輯:PHP 綜合知識

處理大量圖片縮略圖生成是常見需求(如商品圖、用戶頭像)。本文提供一個功能完整的 image 類別,支援本地/遠程圖片來源、自動建立目錄、MD5 亂碼命名避免衝突、等比縮放/裁切、品質控制、GIF/JPG/PNG 多格式處理,並內建快取機制避免重複處理。

類別核心功能總覽

  • 目錄管理:mkdirs() 遞歸建立儲存目錄。
  • 檔案儲存:savefile() 相容 file_put_contents 與舊版 fwrite。
  • 副檔名檢查:getsuffix()、checksuffix() 過濾允許格式。
  • 縮略核心 Mini():支援寬高指定、品質參數、遠程圖片自動下載、比例計算裁切、imagecopyresampled 高品質重採樣。
  • 命名策略:reNames() 產生 {寬}_{高}_{MD5片段}.{副檔名} 格式,含尺寸資訊利於辨識。
  • 快取機制:目標檔案存在且 $over=0 時直接返回路徑,避免重複運算。
class image {
    public $src, $newsrc, $allowtype = [".gif", ".jpg", ".png", ".jpeg"];
    public $regif = 0, $keep = 0, $over = 0;
    public $dir, $newdir;

    public function __construct($olddir = null, $newdir = null) {
        $this->dir = $olddir ?? "./images/temp";
        $this->newdir = $newdir ?? "./images/s";
    }

    public function Mini($src, $w, $h, $q = 80) {
        $this->src = $src; $this->w = $w; $this->h = $h;

        if (strrchr($src, ".") == ".gif" && $this->regif == 0) return $this->src;

        $newsrc = $this->keep == 0 ? $this->reNames($src) 
            : $this->newdir . strrchr(str_replace("\\", "/", $src), "/");

        if (file_exists($newsrc) && $this->over == 0) return $newsrc;

        if (strpos($src, "https://") === 0 && strpos($src, $_SERVER['HTTP_HOST']) === false) {
            $src = $this->getimg($src);
        }

        $arr = getimagesize($src);
        [$width, $height, $type] = [$arr[0], $arr[1], $arr[2]];

        $im = match($type) {
            1 => imagecreatefromgif($src),
            2 => imagecreatefromjpeg($src),
            3 => imagecreatefrompng($src),
            default => return 0,
        };

        // 計算裁切區域:保持目標比例,從源圖中心裁切
        $nim = imagecreatetruecolor($w, $h);
        $k1 = round($h / $w, 2);
        $k2 = round($height / $width, 2);

        if ($k1 < $k2) {
            $width_a = $width; $height_a = round($width * $k1);
            $sw = 0; $sh = ($height - $height_a) / 2;
        } else {
            $width_a = $height / $k1; $height_a = $height;
            $sw = ($width - $width_a) / 2; $sh = 0;
        }

        if (function_exists('imagecopyresampled')) {
            imagecopyresampled($nim, $im, 0, 0, $sw, $sh, $w, $h, $width_a, $height_a);
        } else {
            imagecopyresized($nim, $im, 0, 0, $sw, $sh, $w, $h, $width_a, $height_a);
        }

        if (!is_dir($this->newdir)) mkdir($this->newdir, 0777, true);

        $rs = match($type) {
            1 => imagegif($nim, $newsrc),
            2 => imagejpeg($nim, $newsrc, $q),
            3 => imagepng($nim, $newsrc),
            default => 0,
        };

        imagedestroy($im); imagedestroy($nim);
        return $newsrc;
    }

    // 其他輔助方法:getimg(), reNames(), reImg()...
}

// 使用範例
$img = new image();
echo $img->reImg("images/zht.jpg", 75, 75, 80) . "
"; echo $img->reImg("images/m8920.jpg", 75, 75, 80) . "
";

實務部署建議

✅ 生產環境優化清單
  • 錯誤處理:各 GD 函數回傳值檢查、try-catch 包裹、記錄失敗日誌。
  • 記憶體管理:大圖處理前調整 memory_limit,處理後及時 imagedestroy()。
  • 非同步化:大量圖片建議透過佇列 (Redis/RabbitMQ) + Worker 機制背景處理,避免 HTTP 請求超時。
  • WebP/AVIF 支援:新增 imagecreatefromwebp()、imagewebp() 輸出新一代格式,大幅減小檔案體積。
  • 安全性:遠程下載需驗證 Content-Type、限制檔案大小、禁用 allow_url_fopen 改用 cURL。

此類別為批量縮略圖處理提供了堅實基礎,配合現代化儲存服務 (S3、雲存儲) 與 CDN 整合,可構建高效能圖片處理管線。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved