2017-04-02 96 views
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瀏覽器的網絡選項卡上的樣子:

chrome network

即使需要5秒完成加載,圖像已準備就緒,可見在正常速度下,在大約100毫秒。

您也可以形象地說,文件類型爲「文件」,而不是「圖像」中看到,IDK的原因。

我一直在使用不同的代碼來渲染圖像嘗試,但我得到了相同的行爲:

$fp = fopen($image[0], 'rb'); 
fpassthru($fp); 

我在做什麼錯?我是否缺少一些標題?

謝謝你的時間!

回答

0

沒有什麼錯在你張貼除了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網絡工具故障的可能性。特別是因爲你已經注意到圖像實際上沒有延遲加載。

+0

感謝@paolo! 'while(ob_get_level()> 0){ob_end_flush(); '訣竅。當我在等待答案時,我一直在嘗試,這個頭文件也會在圖像顯示後停止加載:'header(「Connection:close」)',但是在文檔中說'Connection頭中列出的消息頭必須不是包括端到端的頭文件,比如Cache-Control.'所以它可能與我使用的緩存控制頭衝突,idk ...我應該使用flush緩衝區還是添加前面的頭文件?再次感謝您的時間 –

+0

只需刷新緩衝區並退出() – Paolo