Current Location: Home> Latest Articles> How to Get Image Dimensions and File Size in PHP: Practical Guide & Code Examples

How to Get Image Dimensions and File Size in PHP: Practical Guide & Code Examples

gitbox 2025-06-06

Introduction

Image handling is a common task in web development, especially for applications involving uploads or content management. Knowing an image’s dimensions and file size is critical for optimizing layout and performance. In this article, we’ll explore how to use PHP’s built-in functions to obtain this information efficiently.

Using getimagesize() to Get Image Dimensions

PHP’s getimagesize() function is a convenient way to retrieve detailed image metadata. It returns an array with the following information:

  • Width (in pixels)
  • Height (in pixels)
  • Image type code
  • HTML height attribute string (if applicable)
  • HTML width attribute string (if applicable)
  • MIME type as a string
  • Thumbnail info for JPEG (if available)
  • Thumbnail info for SWF (if available)

Here’s a simple example of how to use it for a local image:


$size = getimagesize("example.jpg");
$width = $size[0];
$height = $size[1];

The width and height of example.jpg are stored in $width and $height, respectively.

Getting Remote Image Dimensions

You can also retrieve dimensions of remote images by passing the image URL to getimagesize():


$size = getimagesize("https://example.com/example.jpg");
$width = $size[0];
$height = $size[1];

This will return the dimensions of the image hosted at the provided URL.

Retrieving the Image MIME Type

The getimagesize() function also returns the MIME type of the image, which is useful for validating or setting headers:


$size = getimagesize("example.jpg");
$mime_type = $size['mime'];

For example, this might return image/jpeg or image/png.

Getting File Size in PHP

To get the file size of an image in bytes, use the filesize() function:


$size = filesize("example.jpg");

This returns the file size of example.jpg in bytes.

Formatting File Size in a Readable Format

To display the file size in a human-friendly format such as KB or MB, you can use a custom function like this:


function format_size($bytes) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    $i = 0;
    while ($bytes >= 1024) {
        $bytes /= 1024;
        $i++;
    }
    return round($bytes, 2) . ' ' . $units[$i];
}

$size = filesize("example.jpg");
$formatted_size = format_size($size);

This will output something like 10.5 KB, making the file size easier to understand.

Conclusion

PHP makes it easy to retrieve image size and file information using functions like getimagesize() and filesize(). Whether you're working with local or remote images, these tools help streamline your development process and enhance the efficiency and usability of your application.