Get the width and height of an image in PHP

In this tutorial, we are going to see how to get the width and height of an image in PHP.

Getting the width and the height of an image is an easy task using PHP. PHP already has an inbuilt function getimagesize() which can return an array for an image that contains the size of the image. We just need to pass the image path as a parameter in this function and it will return the array containing image size.

How To Display A Random Image From Directory In PHP?

Let’s see an example of getting the array from PHP getimagesize() function for an image.

Below is PHP the code:

$img_size_array = getimagesize('my_directory/myimg.jpg');
echo "<pre>"; print_r($img_size_array); echo "</pre>";

The above code will return an array something like you can see below:

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

The above array contains the image width in the index 0 and heigh in the index 1. Index number 3 contains both width and height like an HTML attribute. In next step, we are going to take the width and height of the image and display it on the web page.

Below is the complete code that will display the image height and width:


  $img_size_array = getimagesize('my_directory/myimg.jpg');

  $width = $img_size_array[0];
  $height = $img_size_array[1];

  echo "Width is ".$width."px and height is ".$height."px";


The above code will show the image width and height like below:

Width is 625px and height is 420px

So, we have successfully written our simple PHP code that can show the width and height of a particular image.

Set a seasonal image in PHP that will change with the season

Leave a Reply

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