Development

Getting image width, height and file size using PHP

Another easy to do exercise with PHP is getting an image width, height and size.

Getting the image width and height in pixels is done with the function getimagesize(). All that needs defining is the image file or link. Note that getimagesize() downloads the image so bigger image files will take noticeable time.

$image_link = 'imagefile.jpg';
$image_details = getimagesize($image_link);
$width = $image_details[0];
$height = $image_details[1];
echo "$width x $height";

The above PHP code will echo out the width x height for the image specified.

To get the image file size, PHP’s function filesize() is used. As you would expect by the functions name it returns the file size in bytes.

These bytes can be formatted for readability using a function with thanks to Adnan at StackOverflow:

function format_bytes($bytes)//@Adnan StackOverflow
{
    if ($bytes >= 1073741824) {
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        $bytes = $bytes . ' bytes';
    } elseif ($bytes == 1) {
        $bytes = $bytes . ' byte';
    } else {
        $bytes = '0 bytes';
    }
    return $bytes;
}

$size_formatted = format_bytes(filesize($image_link));

This will output something like 1.4 MB or 612 KB etc depending on your image size of course.

Finally to avoid the main error that no image is found at the link, wrap it in a check for valid image:

if (@getimagesize($image_link)) {
//Image exists
} else {
//Does NOT exist
}
$image_link = 'Bridge.jpg';
if (@getimagesize($image_link)) {
    $image_details = getimagesize($image_link);
    $width = $image_details[0];
    $height = $image_details[1];
    $size_formatted = format_bytes(filesize($image_link));
    echo "$width x $height $size_formatted";
} else {//Does NOT exist
    echo "Check your link as no image was found";
}

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago