2010-10-26 54 views
7

我使用php gd調整圖像大小。結果是我想要上傳到Amazon S3的圖像資源。如果我首先將圖像存儲在磁盤上,但是我想直接從內存中將它們上傳,它會很好用。這是可能的,如果我只知道圖像的字節大小。如何用PHP和GD獲取圖像資源大小(以字節爲單位)?

是否有某種方式獲取gd圖像資源的大小(以字節爲單位)?

+0

您無法上傳資源。 – 2010-10-26 12:07:10

回答

12

您可以使用PHP的memory i/o stream來保存圖像並隨後獲取以字節爲單位的大小。

你要做的就是:

$img = imagecreatetruecolor(100,100); 
// do your processing here 
// now save file to memory 
imagejpeg($img, 'php://memory/temp.jpeg'); 
$size = filesize('php://memory/temp.jpeg'); 

現在你應該知道的大小

我不知道任何(GD)方法來獲取圖像資源的大小。

+1

問題是'gd'函數需要一個路徑而不是文件資源來寫入。這應該與[輸出緩衝](http://php.net/manual/en/function.ob-start.php)相反。 – deceze 2010-10-26 12:11:49

+0

@deceze:你應該能夠提供如下路徑:'php:// memory/resource = img.jpeg' – 2010-10-26 12:27:45

+0

非常好,很好的解釋。 – deceze 2010-10-26 12:52:59

-1

將圖像文件以所需格式保存到tmp目錄,然後使用filesize()http://php.net/manual/de/function.filesize.php,然後將其從磁盤上載到S3。

+0

以下是英文版:http://www.php.net/manual/en/function.filesize.php :) – infinity 2010-10-26 12:08:46

+0

將臨時文件保存在磁盤上正是我想要避免的。 – Martin 2010-10-26 12:26:58

+0

爲什麼?這不是一個性能問題,並節省了大量的RAM。 – joni 2010-10-26 12:30:42

0

你可以看看下面的答案尋求幫助。它適用於php中的通用內存更改。儘管可能涉及開銷,但可能更多的是估計。

Getting size of PHP objects

9

我不能寫PHP://內存imagepng,所以我用ob_start(),ob_get_content()結束ob_end_clean()

$image = imagecreatefrompng('./image.png'); //load image 
// do your processing here 
//... 
//... 
//... 
ob_start(); //Turn on output buffering 
imagejpeg($image); //Generate your image 

$output = ob_get_contents(); // get the image as a string in a variable 

ob_end_clean(); //Turn off output buffering and clean it 
echo strlen($output); //size in bytes 
+1

爲什麼不使用像@JonathanWren建議的'ob_get_length'? – Wilt 2015-07-29 13:44:56

5

這也適用於:

$img = imagecreatetruecolor(100,100); 

// ... processing 

ob_start();    // start the buffer 
imagejpeg($img);   // output image to buffer 
$size = ob_get_length(); // get size of buffer (in bytes) 
ob_end_clean();   // trash the buffer 

而現在$size將有您的大小以字節爲單位。

+0

謝謝。這對我有幫助,因爲我需要一種方法來確定文件大小而不上傳它。 – Benjamin 2016-04-12 15:46:21

相關問題