傳統上傳即生成所有規格縮略圖會造成存儲浪費與上傳延遲。採用 Apache Rewrite + PHP 即時生成 策略:
/supload/news/2013/07/21/1.jpg)www/
├── PicThumb.class.php # 縮略圖核心類
├── ThumbConfig.php # 多規格配置
├── upload/ # 原圖存儲
│ └── news/2013/07/21/1.jpg
└── supload/ # 縮略圖輸出目錄(公開訪問)
├── .htaccess # Rewrite 規則
├── watermark.png # 水印文件
└── createthumb.php # 生成入口腳本
<IfModule mod_rewrite.c>
RewriteEngine On
# 文件/鏈接/目錄存在則直接服務
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
# 否則轉發給生成腳本
RewriteRule ^.*$ createthumb.php?path=%{REQUEST_URI} [NC,L]
</IfModule>
<?php
define('WWW_PATH', dirname(dirname(__FILE__)));
require WWW_PATH . '/PicThumb.class.php';
require WWW_PATH . '/ThumbConfig.php';
$logfile = WWW_PATH . '/createthumb.log';
$source_root = WWW_PATH . '/upload/';
$dest_root = WWW_PATH . '/supload/';
$path = isset($_GET['path']) ? $_GET['path'] : '';
if (!$path) exit();
// 解析請求路徑對應的配置
$relative = str_replace($dest_root, '', WWW_PATH . $path);
$type = substr($relative, 0, strpos($relative, '/'));
$config = isset($thumb_config[$type]) ? $thumb_config[$type] : null;
if (!$config || !isset($config['fromdir'])) exit();
// 構建原圖與目標路徑
$source = str_replace('/' . $type . '/', '/' . $config['fromdir'] . '/', $source_root . $relative);
$dest = $dest_root . $relative;
// 生成並輸出
$thumb = new PicThumb($logfile);
$thumb->set_config($config);
if ($thumb->create_thumb($source, $dest)) {
ob_clean();
header('Content-Type: ' . mime_content_type($dest));
exit(file_get_contents($dest));
}
?>
<?php
$thumb_config = [
'news' => [
'fromdir' => 'news', // 原圖子目錄
'type' => 'fit', // 縮放模式:fit/crop/fill
'width' => 100,
'height' => 100,
'bgcolor' => '#FF0000' // fit 模式填充色
],
'news_1' => [
'fromdir' => 'news',
'type' => 'fit',
'width' => 200,
'height' => 200,
'bgcolor' => '#FFFF00'
],
'article' => [
'fromdir' => 'article',
'type' => 'crop', // 裁剪模式
'width' => 250,
'height' => 250,
'watermark' => WWW_PATH . '/supload/watermark.png' // 水印
]
];
(此處省略完整類代碼,核心方法簽名如下)
class PicThumb {
public function __construct($logfile) { /* 初始化日誌 */ }
public function set_config(array $config) { /* 設置縮放參數 */ }
public function create_thumb($source, $dest) {
/* 1. 檢查源文件存在
2. 根據 type 執行:
- fit: 等比縮放至框內,不足填充 bgcolor
- crop: 居中裁剪填滿
- fill: 拉伸填滿
3. 可選添加水印
4. 遞歸創建目標目錄
5. 保存圖片(保持 EXIF 方向)
6. 記錄日誌
*/
}
}
部署後訪問以下 URL 將自動生成對應規格縮略圖:
https://localhost/supload/news/2013/07/21/1.jpg → 100x100 紅色填充https://localhost/supload/news_1/2013/07/21/1.jpg → 200x200 黃色填充https://localhost/supload/article/2013/07/21/2.jpg → 250x250 裁剪+水印try_files 指令替代 Rewrite,效能更高upload/ 目錄禁止直接訪問,僅內部讀取Accept Header 輸出 WebP/AVIF 現代格式這套方案實現了「零配置上傳、按需生成、靜態化緩存」的完美平衡,是圖片密集型應用的標準架構模式。