views:

61

answers:

3

I'm resizing images with php gd. The result is image resources that i want to upload to Amazon S3. It works great if i store the images on disk first but i would like to upload them directly from memory. That is possible if i just know the bytesize of the image.

Is there some way of getting the size (in bytes) of an gd image resource?

A: 

Save the image file in the desired format to a tmp dir, and then use filesize() http://php.net/manual/de/function.filesize.php before uploading it to S3 from disk.

joni
Here is the English version: http://www.php.net/manual/en/function.filesize.php :)
infinity
Saving a temp-file on disk is exactly what i'm trying to avoid here.
Martin
Why? It's not that much a performance issue and saves a lot of RAM.
joni
+3  A: 

You could use PHP's memory i/o stream to save the image to and subsequently get the size in bytes.

What you do is:

$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');

Now you should know the size

I don't know of any (gd)method to get the size of an image resource.

Dennis Haarbrink
The problem is that the `gd` functions expect a path, not a file resource, to write to. This should work with [output buffering](http://php.net/manual/en/function.ob-start.php) instead though.
deceze
@deceze: You should be able to supply a path like: `php://memory/resource=img.jpeg`
Dennis Haarbrink
Excellent, good explanation.
deceze
Ah nice one! This will use double the memory though so it's not optimal but a nice alternative :)
Martin
+1  A: 

You might look at the following answer for help. It works for generic memory changes in php. Although since overhead could be involved it might be more of an estimation.

Getting size of PHP objects

CtRanger