萬盛學電腦網

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

PHP 動態生成圖片縮略圖:GD 庫即時輸出、不佔硬碟空間

應用場景

  • 電商商品圖:原圖 2000px,列表頁只需 200px 縮圖
  • 用戶頭像:上傳後即時生成多種尺寸(32/64/128/256)
  • 文章封面:依版面需求動態裁切比例
  • 避免預生成佔用儲存、同步麻煩

核心架構:thumbs.php 即時輸出

<?php
// thumbs.php
// 使用方式:

// 1. 參數驗證與清洗
$filename = basename($_GET['filename'] ?? ''); // 防止目錄遍歷
$width    = max(1, min(2000, (int)($_GET['width']  ?? 100)));
$height   = max(1, min(2000, (int)($_GET['height'] ?? 100)));
$mode     = $_GET['mode'] ?? 'fit'; // fit | fill | stretch

if (!$filename || !preg_match('/^[\w\-. ]+\.(jpe?g|png|gif|webp)$/i', $filename)) {
    http_response_code(400);
    exit('Invalid filename');
}

$sourcePath = __DIR__ . '/images/' . $filename;
if (!is_file($sourcePath)) {
    http_response_code(404);
    exit('Image not found');
}

// 2. 取得原圖資訊
[$srcW, $srcH, $type] = getimagesize($sourcePath);
if (!$srcW) {
    http_response_code(500);
    exit('Invalid image');
}

// 3. 計算目標尺寸
switch ($mode) {
    case 'fill':   // 裁切填滿(保持比例,超出裁切)
        $ratio = max($width / $srcW, $height / $srcH);
        $dstW = (int)round($srcW * $ratio);
        $dstH = (int)round($srcH * $ratio);
        $srcX = (int)(($srcW - $width / $ratio) / 2);
        $srcY = (int)(($srcH - $height / $ratio) / 2);
        $srcCropW = (int)($width / $ratio);
        $srcCropH = (int)($height / $ratio);
        break;
    case 'stretch': // 強制拉伸(不保持比例)
        $dstW = $width; $dstH = $height;
        $srcX = $srcY = 0; $srcCropW = $srcW; $srcCropH = $srcH;
        break;
    case 'fit':
    default:       // 等比縮放(完整顯示,可能有留白)
        $ratio = min($width / $srcW, $height / $srcH);
        $dstW = (int)round($srcW * $ratio);
        $dstH = (int)round($srcH * $ratio);
        $srcX = $srcY = 0; $srcCropW = $srcW; $srcCropH = $srcH;
        break;
}

// 4. 建立畫布與重採樣
$dstImg = imagecreatetruecolor($width, $height);

// 背景填白(或透明)
if ($type === IMAGETYPE_PNG || $type === IMAGETYPE_GIF || $type === IMAGETYPE_WEBP) {
    imagesavealpha($dstImg, true);
    $transparent = imagecolorallocatealpha($dstImg, 0, 0, 0, 127);
    imagefill($dstImg, 0, 0, $transparent);
} else {
    $white = imagecolorallocate($dstImg, 255, 255, 255);
    imagefill($dstImg, 0, 0, $white);
}

// 載入原圖
$srcImg = match ($type) {
    IMAGETYPE_JPEG => imagecreatefromjpeg($sourcePath),
    IMAGETYPE_PNG  => imagecreatefrompng($sourcePath),
    IMAGETYPE_GIF  => imagecreatefromgif($sourcePath),
    IMAGETYPE_WEBP => imagecreatefromwebp($sourcePath),
    default        => null,
};
if (!$srcImg) { http_response_code(500); exit('Unsupported format'); }

// 重採樣(高品質縮放)
imagecopyresampled(
    $dstImg, $srcImg,
    0, 0, $srcX, $srcY,
    $dstW, $dstH, $srcCropW, $srcCropH
);

// 5. 輸出
header('Content-Type: image/jpeg'); // 統一輸出 JPEG,或根據需求調整
header('Cache-Control: public, max-age=31536000'); // 1 年快取
header('ETag: "' . md5_file($sourcePath) . '"');

imagejpeg($dstImg, null, 85); // 品質 85

// 6. 清理
imagedestroy($srcImg);
imagedestroy($dstImg);
?>

前端調用範例

<!-- 等比縮放,寬 300 高 200 為上限 -->
<img src="thumbs.php?filename=product.jpg&width=300&height=200&mode=fit" alt="商品" />

<!-- 裁切填滿 300x200,適合卡片封面 -->
<img src="thumbs.php?filename=banner.jpg&width=300&height=200&mode=fill" alt="橫幅" />

<!-- 強制拉伸 -->
<img src="thumbs.php?filename=logo.png&width=100&height=100&mode=stretch" alt="Logo" />

效能優化關鍵點

1. 快取策略(關鍵!)

動態生成雖方便,但每次請求都要解碼、縮放、編碼,CPU 開銷大。必須加快取:

<?php
// 簡易檔案快取版本
$cacheDir = __DIR__ . '/cache/thumbs/';
$cacheKey = md5($filename . $width . $height . $mode);
$cacheFile = $cacheDir . $cacheKey . '.jpg';

if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 86400) {
    // 直接輸出快取
    header('Content-Type: image/jpeg');
    header('X-Thumb-Cache: HIT');
    readfile($cacheFile);
    exit;
}

// ... 生成縮圖程式碼 ...
// 最後輸出前存快取
imagejpeg($dstImg, $cacheFile, 85);
imagejpeg($dstImg, null, 85); // 同時輸出給瀏覽器
?>

2. Nginx/Apache 靜態快取規則

# Nginx
location /thumbs.php {
    # 快取生成的縮圖 1 年
    expires 1y;
    add_header Cache-Control "public, immutable";
    
    # 可選:用 try_files 先找快取檔案
    # try_files /cache/thumbs/$arg_filename-$arg_width-$arg_height-$arg_mode.jpg $uri /thumbs.php;
}

3. 並發保護:防止同一圖片同時被多請求生成

<?php
// 簡易檔案鎖
$lockFile = $cacheDir . '.lock.' . $cacheKey;
$fp = fopen($lockFile, 'w');
if (flock($fp, LOCK_EX | LOCK_NB)) {
    // 我們獲得鎖,負責生成
    // ... 生成並存檔 ...
    flock($fp, LOCK_UN);
} else {
    // 等待生成完成(最多 5 秒)
    for ($i = 0; $i < 50; $i++) {
        if (file_exists($cacheFile)) break;
        usleep(100000);
    }
}
fclose($fp);
// 輸出快取檔
readfile($cacheFile);
?>

進階:支援 WebP 輸出(更小體積)

<?php
// 檢查瀏覽器支援
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';
$useWebP = strpos($accept, 'image/webp') !== false;

if ($useWebP && function_exists('imagewebp')) {
    header('Content-Type: image/webp');
    imagewebp($dstImg, null, 80);
} else {
    header('Content-Type: image/jpeg');
    imagejpeg($dstImg, null, 85);
}
?>

常見問題排查

動態縮圖是「以 CPU 換儲存、換維護成本」的經典權衡。配合快取層,能以極低成本支撐百萬級圖片服務。

copyright © 萬盛學電腦網 all rights reserved
現象原因解決
輸出亂碼/破圖輸出前有 echo/空白/錯誤訊息確保 header 前無任何輸出,關閉錯誤顯示
透明背景變黑PNG/GIF 未開啟 alpha 通道imagesavealpha + imagecolorallocatealpha
記憶體耗盡原圖過大(>5000px)預先限制最大尺寸、分塊處理或用 ImageMagick
中文檔名 404URL 編碼/檔案系統編碼不一致統一 UTF-8,用 rawurldecode 解碼參數