Categories: 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…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago