傳統縮圖需預先批次處理。本文實作「依請求動態產生」機制:當縮圖不存在時,透過 Apache Rewrite 導向 PHP 腳本即時生成並輸出,後續請求直接由 Web Server 靜態服務。
原圖: https://example.com/upload/news/2013/07/21/1.jpg
縮圖: https://example.com/supload/news/2013/07/21/1.jpg
↑ 若不存在 → Rewrite → createthumb.php?path=/supload/news/... → 產生 → 輸出
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]
# 其餘導向 PHP 處理
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_path = WWW_PATH . '/upload/';
$dest_path = WWW_PATH . '/supload/';
$path = isset($_GET['path']) ? $_GET['path'] : '';
if (!$path) exit();
// 解析請求路徑對應的規則
$relative_url = str_replace($dest_path, '', WWW_PATH . $path);
$type = substr($relative_url, 0, strpos($relative_url, '/'));
$config = isset($thumb_config[$type]) ? $thumb_config[$type] : '';
if (!$config || !isset($config['fromdir'])) exit();
// 來源/目標檔案路徑
$source = str_replace('/' . $type . '/', '/' . $config['fromdir'] . '/', $source_path . $relative_url);
$dest = $dest_path . $relative_url;
// 產生縮圖
$obj = new PicThumb($logfile);
$obj->set_config($config);
if ($obj->create_thumb($source, $dest)) {
ob_clean();
header('Content-Type: ' . mime_content_type($dest));
exit(file_get_contents($dest));
}
?>
<?php
$thumb_config = array(
'news' => array(
'fromdir' => 'news',
'type' => 'fit',
'width' => 100,
'height' => 100,
'bgcolor' => '#FF0000'
),
'news_1' => array(
'fromdir' => 'news',
'type' => 'fit',
'width' => 200,
'height' => 200,
'bgcolor' => '#FFFF00'
),
'article' => array(
'fromdir' => 'article',
'type' => 'crop',
'width' => 250,
'height' => 250,
'watermark' => WWW_PATH . '/supload/watermark.png'
)
);
/supload/news/2013/07/21/1.jpgcreatethumb.php?path=/supload/news/...type=news,載入對應設定/upload/news/2013/07/21/1.jpgPicThumb 產生縮圖儲存至 /supload/news/...news、news_1)supload 目錄可寫入