Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get image resource size in bytes with PHP and GD?

Tags:

php

image

gd

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?

like image 543
Martin Avatar asked Oct 26 '10 12:10

Martin


People also ask

How to get size of an image in PHP?

The getimagesize() function in PHP is an inbuilt function which is used to get the size of an image. This function accepts the filename as a parameter and determines the image size and returns the dimensions with the file type and height/width of image.

What is use of GD library in PHP?

GD is an open source code library for the dynamic creation of images. GD is used for creating PNG, JPEG and GIF images and is commonly used to generate charts, graphics, thumbnails on the fly.

What are the functions to be used to get the image properties size width and height?

The imagesx() and imagesy() are used to extract the width and height of the images respectively.


3 Answers

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.

like image 53
Dennis Haarbrink Avatar answered Nov 15 '22 21:11

Dennis Haarbrink


I can't write on php://memory with imagepng, so I use ob_start(), ob_get_content() end 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
like image 31
Worms Avatar answered Nov 15 '22 21:11

Worms


This also works:

$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

And now $size will have your size in bytes.

like image 21
Jonathan Wren Avatar answered Nov 15 '22 22:11

Jonathan Wren