萬盛學電腦網

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

PHP 搭配 Nginx 實現高性能動態圖片裁剪方案

前言

早期曾分享過一篇關於高性能 PHP 圖片動態裁剪的文章,當時採用的是 Nginx Cache 搭配 Rewrite 機制,再加上 CDN 加速。但該方案存在一個明顯短板:圖片並未實際生成實體文件,而是以二進制形式暫存於快取中。一旦快取失效,仍需請求 PHP 重新生成,增加了伺服器負擔。

利用業餘時間,我優化了該方案,新增了靜態圖片生成支援,提供三種裁剪模式切換,適用於門戶類網站自動適配圖片尺寸,有效降低伺服器頻寬消耗,滿足業務實際需求。核心圖片處理採用 Imagick 擴展實現。

核心思路

  1. 編寫圖片動態生成腳本,核心邏輯為等比縮放計算與裁剪處理。
  2. 規劃 URL 重寫規則,建立友好的訪問路徑結構。
  3. 配置瀏覽器快取策略,減少重複請求。
  4. 部署上線,完成閉環。

動態裁剪 PHP 腳本實現

核心腳本 resize.php 代碼如下:

ini_set("memory_limit", "80M"); // 設定記憶體上限

// 請求範例:https://yourdomain.com/resize.php?site=www&width=300&height=200&mode=2&path=uploadfile/helloworld.png
// Nginx 重寫規則:
// rewrite ^([^.]*)/s/(.*)/(\d+)x(\d+)-(\d)/(.*) $1/s/resize.php?site=$2&width=$3&height=$4&mode=$5&path=$6 last;

$path = trim($_GET['path']);
$mode = intval($_GET['mode']);
$site = trim($_GET['site']);
$width = intval($_GET['width']);
$height = intval($_GET['height']);

$site_list = ['www' => '/mnt/webroot/test/'];
$orig_dir = dirname(__FILE__);

// 站點驗證
if (!array_key_exists($site, $site_list)) {
    header('HTTP/1.1 400 Bad Request');
    exit();
}

// 模式驗證(0-3)
if ($mode > 3 || $mode < 0) {
    header('HTTP/1.1 400 Bad Request');
    exit();
}

$orig_file = $site_list[$site] . $path;
if (!file_exists($orig_file)) {
    header('HTTP/1.1 404 Not Found');
    exit();
}

$file_ext = '.' . pathinfo($path, PATHINFO_EXTENSION);
$file_name = basename($path, $file_ext);
$save_path = "{$orig_dir}/{$site}/{$width}x{$height}-{$mode}/{$path}";
$save_dir = dirname($save_path);

if (!file_exists($save_dir)) {
    wpx_mkdir($save_dir); // 遞歸建立目錄
}

$target_width = $width;
$target_height = $height;
$new_width = $target_width;
$new_height = $target_height;

$image = new Imagick($orig_file);
list($orig_width, $orig_height, $type, $attr) = getimagesize($orig_file);

// 模式 0:等比縮放(不裁剪)
if ($mode == "0") {
    $new_height = $orig_height * $new_width / $orig_width;
    if ($new_height > $target_height) {
        $new_width = $orig_width * $target_height / $orig_height;
        $new_height = $target_height;
    }
}
// 模式 2:放大並居中裁剪(填滿目標區域)
else if ($mode == "2") {
    $desired_aspect = $target_width / $target_height;
    $orig_aspect = $orig_width / $orig_height;

    if ($desired_aspect > $orig_aspect) {
        $trim = $orig_height - ($orig_width / $desired_aspect);
        $image->cropImage($orig_width, $orig_height - $trim, 0, $trim / 2);
    } else {
        $trim = $orig_width - ($orig_height * $desired_aspect);
        $image->cropImage($orig_width - $trim, $orig_height, $trim / 2, 0);
    }
}

$image->resizeImage($new_width, $new_height, Imagick::FILTER_LANCZOS, 1);
$image->writeImage($save_path);

// 輸出圖片並設定快取頭
header('Content-Type: image/jpeg');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
echo file_get_contents($save_path);
return true;

/**
 * 遞歸建立目錄
 */
function wpx_mkdir($dir, $mode = 0777) {
    if (is_dir($dir) || @mkdir($dir, $mode)) return true;
    if (!wpx_mkdir(dirname($dir), $mode)) return false;
    return @mkdir($dir, $mode);
}

Nginx 配置關鍵點

在 nginx.conf 中配置 location 區塊,實現「靜態文件優先,不存在才動態生成」的策略:

server {
    listen 80;
    server_name test.yourdomain.com;
    root /mnt/webroot/test;
    index index.php;
    expires 30d;

    location /s {
        # 只有當圖片不存在時才調用動態裁剪腳本
        if (!-e $request_filename) {
            rewrite ^([^.]*)/s/(.*)/(\d+)x(\d+)-(\d)/(.*) $1/s/resize.php?site=$2&width=$3&height=$4&mode=$5&path=$6 last;
            break;
        }
    }

    error_page 404 403 402 500 502 503 504 /404.html;
    location = /404.html { }

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

關鍵優化:瀏覽器快取與 CDN 協同

無論採用 PHP 動態生成還是 Nginx 快取,**必須在 PHP 代碼中添加 Last-Modified 頭**:

header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');

此舉對 CDN 節點快取極其關鍵:客戶端首次請求返回 200 OK,後續刷新將命中 304 Not Modified,大幅降低回源壓力與頻寬消耗。

三種裁剪模式說明

模式值行為描述適用場景
0等比縮放,保持原圖比例,完整顯示縮略圖、列表展示
1固定寬高強制拉伸(代碼中未展開)不變形要求低的場景
2居中裁剪填滿,保證輸出尺寸固定Banner、卡片封面、頭像
3智能裁剪(保留重點區域,需擴展)人臉識別、主體偵測

總結

本方案通過「Nginx 靜態文件直出 + PHP 動態生成兜底 + 瀏覽器/CDN 多層快取」的分層架構,實現了高性能、低延遲的圖片動態裁剪服務。Imagick 提供了專業級的圖片處理能力,配合合理的 URL 設計與快取策略,可滿足中大型門戶網站的圖片適配需求。

copyright © 萬盛學電腦網 all rights reserved