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.
PHP’s getimagesize() function is a convenient way to retrieve detailed image metadata. It returns an array with the following information:
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.
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.
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.
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.
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.
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.