phpで画像を一定の横幅にリサイズして出力する。
わりと使うことが多いわりに、毎回あっちこっち探すので。。。
これだけでは動作しないので、とても中途半端な情報で恐縮です。
今回はこれで使った。
詳細
IMG_DIR内のファイルを読み込んで、IMG_Wで指定された横幅にリサイズした画像を出力するとともに、CACHE_DIR内にリサイズ後の画像を保存する。
mod_rewriteと組み合わせることで、次回以降は普通に画像が出力されるので、phpスクリプトのオーバーヘッドがない。
//
// display image data
//
function show_image(){
$cache_dir = CACHE_DIR;
if( !is_dir($cache_dir) && !is_writable($cache_dir) ){
if( !mkdir($cache_dir) ){
trigger_error($cache_dir.' is not writable', E_USER_ERROR);
exit;
}
}
$fname = basename($_SERVER['REQUEST_URI']);
$cache = $cache_dir . '/' . $fname;
if(is_file(IMG_DIR.'/'.$fname)){
list($w,$h) = getimagesize(IMG_DIR.'/'.$fname);
$bin = file_get_contents(IMG_DIR.'/'.$fname);
$_w = IMG_W;
$resize = $_w / $w;
if( $resize < 1 ){
$width = round($w * $resize);
$height = round($h * $resize);
$im = imagecreatetruecolor($width, $height);
$_im = imagecreatefromstring($bin);
imagecopyresampled($im, $_im, 0, 0, 0, 0, $width, $height, $w, $h);
header('Content-type: image/jpeg');
imagejpeg($im, $cache);
print file_get_contents($cache);
}else{
$fp = fopen($cache, 'w');
fwrite($fp, $bin);
fclose($fp);
header('Content-type: image/jpeg');
print $bin;
}
exit;
} else {
header('Content-type: image/jpeg');
readfile(IMG_NOTFOUND);
exit;
}
}
.htaccessは以下のような感じ
# BEGIN WordPress
RewriteEngine On
RewriteBase /twt/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /twt/index.php [L]
# END WordPress