我只是做:
<img src="/thumbnail.php?thumb=mybigpicture.ext" ... />
这就是我的做法。请注意,此实现会缩放图像,无论它们是宽于高还是反之亦然,并且与大多数 PHP 尝试不同,它在缩放方面做得不错。
<?php
function thumb_image($request = "") {
$cfgthumb['folder'] = "/images/cache";
$cfgthumb['height'] = 150;
$cfgthumb['width'] = 200;
$cfgthumb['error'] = "/images/error.jpg";
$cfgthumb['default'] = "/images/notfound.jpg";
$thumb = $cfgthumb['folder'] . "/" . md5($request);
header("Content-Type: image/jpeg");
if (is_readable($thumb)) echo file_get_contents($thumb);
elseif (is_readable($request)) {
$extension = strtolower(end(explode(".", $request)));
switch ($extension) {
case "gif":
$simage = imagecreatefromgif($request);
break;
case "jpeg":
case "jpg":
$simage = imagecreatefromjpeg($request);
break;
case "png":
$simage = imagecreatefrompng($request);
break;
}
if ($simage) {
$simage_width = imagesx($simage);
$simage_height = imagesy($simage);
if (($simage_width > $cfgthumb['width']) || ($simage_height > $cfgthumb['height'])) {
if ($simage_width > $simage_height) {
$dimage_width = $cfgthumb['width'];
$dimage_height = floor($simage_height * ($cfgthumb['width'] / $simage_width));
} else {
$dimage_width = floor($simage_width * ($cfgthumb['height'] / $simage_height));
$dimage_height = $cfgthumb['height'];
}
} else {
$dimage_width = $simage_width;
$dimage_height = $simage_height;
}
$dimage = imagecreatetruecolor($dimage_width, $dimage_height);
imagegammacorrect($simage, 2.2, 1.0);
imagecopyresampled($dimage, $simage, 0, 0, 0, 0, $dimage_width, $dimage_height, $simage_width, $simage_height);
imagegammacorrect($dimage, 1.0, 2.2);
imagejpeg($dimage, $thumb, 100);
imagejpeg($dimage, NULL, 100);
imagedestroy($simage);
imagedestroy($dimage);
} else echo file_get_contents($cfgthumb['error']);
} else echo file_get_contents($cfgthumb['default']);
}
?>