1
我用下面的代碼,以使我的圖片:完美渲染圖像PHP的加載速度慢於鉻
// 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,但同時也需要100毫秒,在IE和Firefox加載,需要5秒鐘才能在Chrome中加載。這就是Chrome瀏覽器的網絡選項卡上的樣子:
即使需要5秒完成加載,圖像已準備就緒,可見在正常速度下,在大約100毫秒。
您也可以形象地說,文件類型爲「文件」,而不是「圖像」中看到,IDK的原因。
我一直在使用不同的代碼來渲染圖像嘗試,但我得到了相同的行爲:
$fp = fopen($image[0], 'rb');
fpassthru($fp);
我在做什麼錯?我是否缺少一些標題?
謝謝你的時間!
感謝@paolo! 'while(ob_get_level()> 0){ob_end_flush(); '訣竅。當我在等待答案時,我一直在嘗試,這個頭文件也會在圖像顯示後停止加載:'header(「Connection:close」)',但是在文檔中說'Connection頭中列出的消息頭必須不是包括端到端的頭文件,比如Cache-Control.'所以它可能與我使用的緩存控制頭衝突,idk ...我應該使用flush緩衝區還是添加前面的頭文件?再次感謝您的時間 –
只需刷新緩衝區並退出() – Paolo