2013-01-31 27 views
4

可能重複:
How to get image resource size in bytes with PHP and GD?PHP:我怎樣才能獲得動態生成的圖像在PHP中的字節大小?

是否有可能得到使用PHP對象$圖像文件的大小(而非圖像尺寸大小)?我想將此添加到我的「Content-Length:」標題中。

$image = imagecreatefromjpeg($reqFilename); 
+0

您應該閱讀更多關於http://www.php.net/manual/en/ref.outcontrol.php的內容,例如'ob_start()','ob_clean()','ob_flush()'等 – Cyclonecode

回答

2

你可以只使用filesize()此:

// returns the size in bytes of the file 
$size = filesize($reqFilename); 

當然,上面會,如果調整後的圖像存儲在磁盤上,如果您將您的來電imagecreatefromjpeg()後調整圖像大小的一個只工作那麼你應該用@One招數Ponys解決方案去做這樣的事情:

// load original image 
    $image = imagecreatefromjpeg($filename); 
    // resize image 
    $new_image = imagecreatetruecolor($new_width, $new_height); 
    imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
    // get size of resized image 
    ob_start(); 
    // put output for image in buffer 
    imagejpeg($new_image); 
    // get size of output 
    $size = ob_get_length(); 
    // set correct header 
    header("Content-Length: " . $size); 
    // flush the buffer, actually send the output to the browser 
    ob_end_flush(); 
    // destroy resources 
    imagedestroy($new_image); 
    imagedestroy($image); 
+1

只需添加一個註釋,即動態生成的圖像應先存儲在服務器上的文件中,以便在將'filesize'發送到客戶端之前使用'filesize'。 – brezanac

+1

這將只獲得存儲的圖像的大小。然而,如果我修改圖像...大小會改變。 – user2030856

+0

我需要在「imagejpeg($ new_image);」之前設置標題。 – user2030856

3

我認爲這應該工作:

$img = imagecreatefromjpeg($reqFilename); 

// capture output 
ob_start(); 

// send image to the output buffer 
imagejpeg($img); 

// get the size of the o.b. and set your header 
$size = ob_get_length(); 
header("Content-Length: " . $size); 

// send it to the screen 
ob_end_flush(); 
+0

對於'ob_'部分爲+1,但是如果文件已經存儲在磁盤上,只要執行'filesize()'就可以了。如果他在將圖像發送到瀏覽器之前調整大小,裁剪或執行一些其他操作,那麼您的解決方案顯然是最好的=) – Cyclonecode

+0

這取決於他顯示的是哪個圖像。如果它不是原始文件,那麼文件大小將有所不同,因爲gd將重新壓縮jpeg ... –

+0

我需要在「imagejpeg($ new_image);」之前設置標題 – user2030856

相關問題