Get the image size (height and width) in PHP

In this tutorial, I am going to tell you how to get the size of an image using PHP. The code snippets I am going to show you will retrieve the height and width of a given image file path.

There is a PHP function already available which will let you know the size of a given image file. The function is getimagesize() which will return an array that contains the height and width of an image file. It will also return some other properties, but here we will only take the image height and the width.

Display an image from base64 code in HTML

Get country data on clicking on map – PHP source code

Suppose we want to get the size of an image image_file.jpg which is inside the directory image. Then we need to pass the file into the PHP getimagesize function just like below:

$imgsize_arr = getimagesize('image/image_file.jpg');

We have store the array data of coming from getimagesize function inside the variable $imgsize_arr.

If we want to see the size array data then we can see it by providing the code that you can see below:

echo "<pre>"; print_r($imgsize_arr); echo "</pre>";

The above code will return array data that looks like below:

    [0] => 727
    [1] => 640
    [2] => 2
    [3] => width="727" height="640"
    [bits] => 8
    [channels] => 3
    [mime] => image/jpeg

In the array, you can see that the width of the image is available in the index 0 and the width in the index 1 of the array.

Now, let’s get the height and width from the array.

$img_width = $imgsize_arr[0];
$img_height = $imgsize_arr[1];

Complete and final code to simply display image width and height

Below is the PHP code which will display the image height and width on the screen:

$imgsize_arr = getimagesize('image/image_file.jpg');

$img_width = $imgsize_arr[0];
$img_height = $imgsize_arr[1];

echo "Image width: ".$img_width."<br/>Image height:".$img_height;

As you can see that it is just a few lines of code which is easily retrieving the size of an image. It is simpler and easier than we can think. isn’t it?

AJAX search from MySQL database in PHP example

Now you can use this method anywhere where you need to know the size of an image or you have to make your logic that is base on the size of the image.

Leave a Reply

Your email address will not be published. Required fields are marked *