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.
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:
Array (  => 625  => 420  => 2  => 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:
<?php $img_size_array = getimagesize('my_directory/myimg.jpg'); $width = $img_size_array; $height = $img_size_array; 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.