【问题标题】:Rendered image php slow loading in chrome渲染图像php在chrome中加载缓慢
【发布时间】: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


    【解决方案1】:

    除了Content-Length 标头必须仅指定字节数(不包括单词字节)之外,您发布的代码没有任何问题。

    header("Content-Length: $size");
    

    即使有这个小错误,但您的代码应该可以正常运行。

    我有一些渲染图像的代码,我用你的确切标题(包括“字节”错误)进行了尝试,并在 Chrome 网络工具中检查了结果。图片加载正常。

    说我会尝试在readfile()之后添加此代码的另一件事

    // Flush (if any) all the buffers
    while( ob_get_level() > 0 ) { ob_end_flush(); }
    
    // Ensure script execution terminates here
    exit();
    

    如果您仍然遇到此问题,我会考虑这可能只是 Chrome 网络工具中的一个故障。尤其是因为您已经注意到图像实际上是在没有延迟的情况下加载的。

    【讨论】:

    • 谢谢@paolo! while( ob_get_level() > 0 ) { ob_end_flush(); } 成功了。当我在等待答案时,我一直在尝试,这个头在图像显示后也会停止加载:header("Connection: close") 但在文档中说Message headers listed in the Connection header MUST NOT include end-to-end headers, such as Cache-Control. 所以它可能与我使用的缓存控制头冲突,idk ...我应该使用刷新缓冲区还是添加前一个标头?再次感谢您的宝贵时间
    • 只需刷新缓冲区并退出()
    猜你喜欢
    • 2015-04-15
    • 2013-11-25
    • 2018-01-22
    • 1970-01-01
    • 2021-05-19
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    相关资源
    最近更新 更多