Hi i have a website in which i make the images with the use of php GD library, i want to know that how can i get the size(in KB or MB) of these random size images. please anyone know about it.
2 Answers
You can get the file size of an image by doing this:
$image_size_in_bytes = filesize($path_to_image);
To get the file size of an image using a URL, use this code: (Note you must have the cURL extension installed)
<?php
// URL to file (link)
$file = 'http://example.com/file.zip';
$ch = curl_init($file);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
// Contains file size in bytes
$contentLength = (int)$matches[1];
}
?>
Read more here.

- 1,658
- 8
- 20
-
Not for HTTP resources, though. – Pekka Jan 15 '13 at 18:40
-
i am not store these images in server, these are only generated with the help of PHP GD Library. – Rishi Jan 15 '13 at 18:46
-
oh, uhmm, could you post some code? The code you use to generate the images. – user1909426 Jan 15 '13 at 18:47
-
– Rishi Jan 16 '13 at 10:22
PHP doesn't have a way to get information about the size of a variable, exactly. One way to get around this is by checking memory usage before and after you generate the image for use as an approximation.
Another way would be to build the image, then set the JPEG/GIF/PNG/etc. data to a variable. Use strlen to get the size of that string in bytes, which will be your image size. I'm not sure how to get the string of data from GD without setting up an output buffer, echo-ing the GD variable, then closing and capturing the buffer; the only other output I know of would be to write it to disk. Which brings us to...
Save the image file to a temporary directory, then get the file size with the filesize function. This will be the most accurate, because when you write the image you will also be setting the type of image file to write, which has an effect on the size. It's also going to involve a lot more disk activity on your server.