萬盛學電腦網

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

PHP 圖片自動裁切/縮放方案:動態尺寸、Apache Rewrite、GD 裁切全流程

門戶/電商網站同一張圖需在多處以不同尺寸、比例顯示(列表圖、詳情圖、縮圖)。固定生成幾套縮略圖不夠靈活,且浪費儲存。本文實現按需動態生成、首次生成後靜態化、Apache Rewrite 透明分發的完整方案。

架構流程

  1. 模板/業務代碼呼叫 `crop_img($src, $w, $h)` 得到帶尺寸後綴的 URL:
    `/data/attachment/forum/abc_200_100.jpg`
  2. Apache 檢測該檔案不存在 → Rewrite 到 `images.php?url=...`
  3. `images.php` 解析尺寸、讀取原圖、GD 裁切/縮放、輸出並保存靜態檔
  4. 下次請求直接命中靜態檔,完全繞過 PHP,效能等同靜態資源

1. 產生帶尺寸的 URL Helper

<?php
function crop_img(string $src, int $w = 200, int $h = 200): string
{
    $info = parse_url($src);
    // 外鏈直接返回
    if (!empty($info['host']) && $info['host'] !== $_SERVER['HTTP_HOST']) return $src;

    $pos = strrpos($src, '.');
    if ($pos === false) return $src;
    return substr($src, 0, $pos) . "_{$w}_{$h}" . substr($src, $pos);
}

// 模板直接輸出 <img> 標籤
function img_tag(string $src, int $w, int $h): void
{
    echo '<img src="' . htmlspecialchars(crop_img($src, $w, $h)) . '" width="' . $w . '" height="' . $h . '" />';
}
?>

2. Apache Rewrite 規則(.htaccess 或 vhost)

<IfModule mod_rewrite.c>
RewriteEngine On
# 僅當檔案/目錄不存在時轉發
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# data/attachment/ 開頭的帶尺寸圖片轉發到 images.php
RewriteRule ^data/attachment/(.*)$ images.php?url=$1 [L,QSA]
</IfModule>

3. 核心處理腳本:`images.php`

<?php
// 入口防護
if (empty($_GET['url'])) exit('Missing url');

$url = $_GET['url'];
$basePath = __DIR__ . '/data/attachment/';

// 還原原圖路徑:移除 _W_H 後綴
$srcPath = $basePath . preg_replace('/_\\d+_\\d+(\\.[^.]+)$/', '$1', $url);
$destPath = $basePath . $url;

if (!file_exists($srcPath)) { output404(); exit; }

// 解析尺寸
if (!preg_match('/_(\\d+)_(\\d+)(\\.[^.]+)$/', $url, $m)) { output404(); exit; }
$w = (int)$m[1]; $h = (int)$m[2];

// 生成縮略圖
thumb($srcPath, $w, $h, $destPath, 'crop', 85);

// 直接輸出給瀏覽器(首次請求)
header('Content-Type: image/jpeg');
readfile($destPath);

function thumb(string $src, int $w, int $h, string $dest, string $mode = 'crop', int $quality = 85): void
{
    $info = getimagesize($src);
    if (!$info) throw new RuntimeException('Invalid image');
    [$sw, $sh, $type] = $info;

    $srcImg = match ($type) {
        IMAGETYPE_JPEG => imagecreatefromjpeg($src),
        IMAGETYPE_PNG  => imagecreatefrompng($src),
        IMAGETYPE_GIF  => imagecreatefromgif($src),
        IMAGETYPE_WEBP => imagecreatefromwebp($src),
        default => throw new RuntimeException('Unsupported type'),
    };

    $dstImg = imagecreatetruecolor($w, $h);
    // 保持透明度
    if (in_array($type, [IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP], true)) {
        imagealphablending($dstImg, false);
        imagesavealpha($dstImg, true);
        $transparent = imagecolorallocatealpha($dstImg, 255, 255, 255, 127);
        imagefill($dstImg, 0, 0, $transparent);
    } else {
        imagefill($dstImg, 0, 0, imagecolorallocate($dstImg, 255, 255, 255));
    }

    // 計算裁切/縮放座標
    if ($mode === 'crop') {
        $srcRatio = $sw / $sh;
        $dstRatio = $w / $h;
        if ($srcRatio > $dstRatio) {
            // 原圖較寬:高度滿屏,寬度居中裁切
            $cropH = $sh;
            $cropW = $sh * $dstRatio;
            $sx = ($sw - $cropW) / 2;
            $sy = 0;
        } else {
            // 原圖較高:寬度滿屏,高度居中裁切
            $cropW = $sw;
            $cropH = $sw / $dstRatio;
            $sx = 0;
            $sy = ($sh - $cropH) / 2;
        }
        imagecopyresampled($dstImg, $srcImg, 0, 0, $sx, $sy, $w, $h, $cropW, $cropH);
    } else {
        // scale:等比縮放,不足留白
        $scale = min($w / $sw, $h / $sh);
        $nw = (int)($sw * $scale);
        $nh = (int)($sh * $scale);
        $dx = (int)(($w - $nw) / 2);
        $dy = (int)(($h - $nh) / 2);
        imagecopyresampled($dstImg, $srcImg, $dx, $dy, 0, 0, $nw, $nh, $sw, $sh);
    }

    // 輸出並保存
    imagejpeg($dstImg, null, $quality);      // 直接輸出
    imagejpeg($dstImg, $dest, $quality);     // 保存靜態檔
    imagedestroy($srcImg);
    imagedestroy($dstImg);
}

function output404(): void
{
    http_response_code(404);
    $default = __DIR__ . '/media/images/nopic.jpg';
    if (file_exists($default)) {
        header('Content-Type: image/jpeg');
        readfile($default);
    }
}
?>

關鍵優化點

  • 首次生成後靜態化:Rewrite 條件 `!-f` 確保二次請求直接由 Apache/Nginx 靜態服務,零 PHP 開銷。
  • 支援透明背景:PNG/GIF/WebP 保持 Alpha 通道,不變黑底。
  • 防盜鏈/濫用:可在 `images.php` 加入 Referer 檢查、速率限制、簽名驗證。
  • 清理策略:定期掃描刪除超過 N 天未訪問的衍生圖,或配合 CDN 邊緣緩存。

Nginx 版 Rewrite(若用 Nginx + PHP-FPM)

location ~ ^/data/attachment/(.+)_(\d+)_(\d+)\.(jpg|png|gif|webp)$ {
    try_files $uri @image_gen;
}
location @image_gen {
    fastcgi_pass php-fpm;
    fastcgi_param SCRIPT_FILENAME $document_root/images.php;
    fastcgi_param QUERY_STRING url=$1_$2_$3.$4;
    include fastcgi_params;
}

此方案已在百萬級 PV 站點穩定運行,完美平衡靈活度與效能。

copyright © 萬盛學電腦網 all rights reserved