【发布时间】:2017-08-27 14:51:03
【问题描述】:
我正在使用下一个代码来渲染我的图像:
// 1. Check if image exists
$image = glob("public/images/$category/$id/$name.*");
// Image exists
if(count($image) === 1) {
// 2. Get file extension
$path_parts = pathinfo($image[0]);
// 3. Add the content type to the header
switch(strtolower($path_parts['extension']))
{
case "gif":
header("Content-type: image/gif");
break;
case "jpg":
case "jpeg":
header("Content-type: image/jpeg");
break;
case "png":
header("Content-type: image/png");
break;
case "bmp":
header("Content-type: image/bmp");
break;
case "svg":
header("Content-type: image/svg+xml");
break;
default:
self::setNotFoundHeaders();
break;
}
// 4. Set the rest of the Header information
header("Expires: Mon, 1 Jan 2099 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
// 5. Get the size for content length
$size= filesize($image[0]);
header("Content-Length: $size bytes");
// 6. Output the file contents
readfile($image[0]);
}
图像在 IE、Chrome 和 Firefox 中完美加载,但在 IE 和 Firefox 中加载需要 100 毫秒,而在 Chrome 中加载需要 5 秒。这是 Chrome 的网络标签的样子:
即使完成加载需要 5 秒,图像也已准备好并以正常速度可见,大约需要 100 毫秒。
您还可以在图像中看到文件类型是“文档”而不是“图像”,我知道为什么。
我尝试使用不同的代码来渲染图像,但我得到了相同的行为:
$fp = fopen($image[0], 'rb');
fpassthru($fp);
我做错了什么?我错过了一些标题吗?
感谢您的宝贵时间!
【问题讨论】:
标签: php image google-chrome header render