usualoma
12/7/2009 - 7:09 AM

gistfile1.php

<?php

function create_cache($file, $cachefile) {
	$x = 240; // 横サイズ
	$y = 320; // 縦サイズ
	$q = 60;  // 画質

	$size = getimagesize($file);

	if($size[0] > $x){

		$y = $x * $size[1] / $size[0];

	} elseif($size[1] > $y){

		$x = $y * $size[0] / $size[1];

	} else{

		$x = $size[0];
		$y = $size[1];
	}

	$img1 = ImageCreateFromJPEG($file);
	$img2 = imageCreatetRuecolor($x, $y);

	imageCopyResampled($img2, $img1, 0, 0, 0, 0, $x, $y, $size[0], $size[1]);

	imagejpeg($img2, $cachefile, $q);

	imagedestroy($img1);
	imagedestroy($img2);
}

function cache_filename($file) {
	return dirname(__FILE__) . '/cache/' . $file;
}

function clear_cache() {
	# 一日前
	$threshold = time() - 60*60*24;

	foreach (glob(dirname(__FILE__) . '/cache/*') as $f) {
		$stat = stat($f);
		# $threshold より前の時間であれば削除
		if ($stat['mtime'] < $threshold) {
			unlink($f);
		}
	}
}

$file = $_GET['file']; // 画像ファイル

if(is_file($file)){
	$cachefile = cache_filename($file);
	if (! file_exists($cachefile)) {
		create_cache($file, $cachefile);
	}

	clear_cache();

	header("Content-type: image/jpeg");
	readfile($cachefile);
}