1

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.

Rishi
  • 123
  • 10

2 Answers2

1

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.

user1909426
  • 1,658
  • 8
  • 20
0

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.

Community
  • 1
  • 1
Mechcozmo
  • 303
  • 1
  • 7