我有一个PHP脚本被称为用?IMG =参数。
该参数的值是一个图像的(urlencoded进行)URL。
我的脚本检查,如果图像已存储在我的服务器。
如果没有 - 它下载它。 之后,它可选择调整图像大小,并将其发送到标准输出,即返回给请求的浏览器,用的Content-Type和Last-Modified头前置:
Connection:close
Content-Type:image/jpeg
Date:Fri, 01 Jun 2012 08:28:30 GMT
Last-Modified:Fri, 01 Jun 2012 08:02:44 GMT
Server:Apache/2.2.15 (CentOS)
Transfer-Encoding:chunked
X-Powered-By:PHP/5.3.3
这是需要要解决一些问题,跨域,并很适合我,因为超过一年:
不过,我想补充的功能来处理传入的If-Modified-Since头-发送未修改304响应。
我的问题是:
1)是,即使在PHP可能,在运行Apache的时候?
2)如何处理(即分析和生产)最好的PHP这里的日期?
奖金问题)如何添加一个Content-Length头调整大小的图像?
我的代码如下(我省略了卷曲下载部分):
<?php
define('CACHE_DIR', '/var/www/cached_avatars/');
$img = urldecode($_GET['img']);
$cached = CACHE_DIR . md5($img);
# omitted downloading part for brevity
$readfh = fopen($cached, 'rb');
if ($readfh) {
flock($readfh, LOCK_SH);
$size = getimagesize($cached);
$w = $size[0];
$h = $size[1];
$type = $size[2];
$mime = $size['mime'];
# find the downscale factor to fit image into $maxw x $maxh
$scale = max($w / $maxw, $h / $maxh);
header('Content-Type: ' . $size['mime']);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($cached)));
$length = filesize($cached);
$buf = fread($readfh, $length);
fclose($readfh);
# the image is smaller than $maxw x $maxh, do not scale up
if ($scale <= 1) {
header('Content-Length: ' . $length);
print($buf);
return;
}
$tw = $w / $scale;
$th = $h / $scale;
$image = imagecreatefromstring($buf);
$thumb = imagecreatetruecolor($tw, $th);
imagecopyresampled($thumb, $image, 0, 0, 0, 0, $tw, $th, $w, $h);
imagedestroy($image);
# How to add Content-Length here, after image resizing?
if (IMAGETYPE_JPEG == $type)
imagejpeg($thumb, null, 75);
else if (IMAGETYPE_PNG == $type)
imagepng($thumb, null, 9);
else if (IMAGETYPE_GIF == $type)
imagegif($thumb, null);
imagedestroy($thumb);
}
?>