以下是我使用的脚本。您可以根据自己的需要对其进行调整。
/
使用以下代码放入 .htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^imgresize/(.+)$ imgresize/imgresize.php
以下代码在/imgresize/imgresize.php
<?php
// no image requested
if(!isset($_SERVER['REQUEST_URI']) || empty($_SERVER['REQUEST_URI'])) {
header('HTTP/1.0 404 Not Found');
exit;
}
// thumbnail already exists (should never be called as the .htaccess is handling this)
if(file_exists('../'.$_SERVER['REQUEST_URI'])) {
header('Content-type: image');
readfile('../'.$_SERVER['REQUEST_URI']);
exit;
}
// extract new width, new height and filename from request
preg_match_all('%/imgresize/([0-9]+)x([0-9]+)/(.+)$%isU', $_SERVER['REQUEST_URI'], $matches);
$new_width = $matches[1][0];
$new_height = $matches[2][0];
$filename = $matches[3][0];
// file doesn't exist
if(!file_exists('../'.$filename)) {
header('HTTP/1.0 404 Not Found');
exit;
}
// get width, height and file format from the original image
list($ori_width, $ori_height, $type, $attr) = getimagesize('../'.$filename);
// create new image
if($type == IMAGETYPE_JPEG) {
$ori_image = imagecreatefromjpeg('../'.$filename);
}
elseif( $type == IMAGETYPE_GIF ) {
$ori_image = imagecreatefromgif('../'.$filename);
}
elseif( $type == IMAGETYPE_PNG ) {
$ori_image = imagecreatefrompng('../'.$filename);
}
// calculate new image ratio
$src_x = $src_y = 0;
if($ori_height/$new_height > $ori_width/$new_width) {
$old_height = $ori_height;
$ori_height = $ori_width/($new_width/$new_height);
$src_y = $old_height/2 - $ori_height/2;
}
else {
$old_width = $ori_width;
$ori_width = $ori_height/($new_height/$new_width);
$src_x = $old_width/2 - $ori_width/2;
}
// resize original image
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $ori_image, 0, 0, $src_x, $src_y, $new_width, $new_height, $ori_width, $ori_height);
// create path
$new = $new_width.'x'.$new_height.'/'.$filename;
$parts = explode('/', $new);
$path = '';
for($i=0;$i<sizeof($parts)-1;$i++) {
$path .= $parts[$i].'/';
if(!file_exists($parts[$i])) {
mkdir($path);
}
}
// save the created image
imagejpeg($new_image, $new, 90);
// sent the created image to the user
header('Content-Type: image');
imagejpeg($new_image, null, 90);
?>
现在将图像路径从 eg 更改/images/frontpage/head.jpg
为/imgresize/300x500/images/frontpage/head.jpg
(300=width, 500=height)。如果图像已经调整大小,则根本不会调用 PHP 脚本(RewriteCond %{REQUEST_FILENAME} !-f
在 .htaccess 中),只会将图像提供给用户。如果调整大小的图像不存在,它将被创建,另存为/imgresize/300x500/images/frontpage/head.jpg
(因此来自第一个请求的虚拟路径将成为所有后续请求的真实路径)并发送给用户。