我使用php gd調整圖像大小。結果是我想要上傳到Amazon S3的圖像資源。如果我首先將圖像存儲在磁盤上,但是我想直接從內存中將它們上傳,它會很好用。這是可能的,如果我只知道圖像的字節大小。如何用PHP和GD獲取圖像資源大小(以字節爲單位)?
是否有某種方式獲取gd圖像資源的大小(以字節爲單位)?
我使用php gd調整圖像大小。結果是我想要上傳到Amazon S3的圖像資源。如果我首先將圖像存儲在磁盤上,但是我想直接從內存中將它們上傳,它會很好用。這是可能的,如果我只知道圖像的字節大小。如何用PHP和GD獲取圖像資源大小(以字節爲單位)?
是否有某種方式獲取gd圖像資源的大小(以字節爲單位)?
您可以使用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)方法來獲取圖像資源的大小。
將圖像文件以所需格式保存到tmp目錄,然後使用filesize()http://php.net/manual/de/function.filesize.php,然後將其從磁盤上載到S3。
你可以看看下面的答案尋求幫助。它適用於php中的通用內存更改。儘管可能涉及開銷,但可能更多的是估計。
我不能寫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
爲什麼不使用像@JonathanWren建議的'ob_get_length'? – Wilt 2015-07-29 13:44:56
這也適用於:
$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
將有您的大小以字節爲單位。
謝謝。這對我有幫助,因爲我需要一種方法來確定文件大小而不上傳它。 – Benjamin 2016-04-12 15:46:21
您無法上傳資源。 – 2010-10-26 12:07:10