To get the image height, image width, and image file type in php, we can use the php getimagesize() function.

$image_information = getimagesize("sample_image.png");
print_r($image_information);

// Output:
Array ( [0] => 500
        [1] => 250 
        [2] => 3 
        [3] => width="500" height="250" 
        [bits] => 8 
        [mime] => image/png )

Many times when designing web pages, we work with images and need to ensure that we are serving the appropriate size and type of image.

With the php getimagesize() function, we can pass a valid image URL and get the image height, image width, and image mime type.

From the php documentation, all we need is a valid file name to call getimagesize() and if the file name is valid, we will receive an array of the image information.

getimagesize(string $filename, array &$image_info = null): array|false

For most image types, the getimagesize() returns an array which contains the image height, image width, image HTML attr string, and image mime type.

If we want to just see this information, we can use the php print_r() function.

$image_information = getimagesize("sample_image.png");
print_r($image_information);

// Output:
Array ( [0] => 500
        [1] => 250 
        [2] => 3 
        [3] => width="500" height="250" 
        [bits] => 8 
        [mime] => image/png )

If you want to use the variables in the return array, we can use the list php language construct.

$image_information = getimagesize("sample_image.png");
list($width, $height, $type, $attr) = $image_information;

echo "Width: " . $width  . "n";
echo "Height: " . $height  . "n";
echo "Type: " . $type  . "n";
echo "Attr: " . $attr  . "n";

//Output:

Width: 500
Height: 250
Type: 3
Attr: width="500" height="250"

Using getimagesize() with a URL in php

We can use the php getimagesize() function to get the image size information from any valid file including those online.

Let’s say I have the following image:

gears

If I wanted to get the information from the following image on this website, I can do that in the following way in php:

$image_information = getimagesize("https://daztech.com/wp-content/uploads/2024/02/tpe-main.png");
list($width, $height, $type, $attr) = $image_information;

echo "Width: " . $width  . "n";
echo "Height: " . $height  . "n";
echo "Type: " . $type  . "n";
echo "Attr: " . $attr  . "n";

//Output:

Width: 500
Height: 497
Type: 3
Attr: width="500" height="497"

One thing to note here is that you may have to enable the ability for your php server to handle url_fopen in the php.ini file (from Stack Overflow answer):

allow_url_fopen = 1 // 0 for Off and 1 for On Flag
allow_url_include = 1 // 0 for Off and 1 for On Flag

Hopefully this article has been beneficial for you to understand how to use getimagesize() to get image information in php.

Categorized in:

PHP,

Last Update: March 1, 2024