PHP Get Image Width And Height
Posted by in PHP September 4, 2011 Leave a comment

There is a PHP function: GetImageSize that returns the actual dimensions (width & height) as well as the type (GIF, PNG, JPG, SWF, PSD, BMP, etc) of a particular image.

The function is useful when you want to resize or generate thumbnail of an image, you may need to determine its width and height. It’s also useful when you want to display a dynamic image (be downloaded from an external resource or uploaded by user) on the HTML page.

PHP Get Image Width And Height – Example

<?php
	$image_name = "Desert.jpg";
 
	list($width, $height, $type, $sizes) = GetImageSize($image_name);
 
	echo "width: " . $width . "<br>";
	echo "height: " . $height . "<br>";
	echo "type: " . $type . "<br>";
	echo "sizes: " . $sizes . "<br>";
?>

Note: flag for image type:

1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(orden de bytes intel), 8 = TIFF(orden de bytes motorola), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM.

Output of the example:

width: 1024
height: 768
type: 2
sizes: width="1024" height="768"

Display Dynamic Image With Width And Height

<?php
	echo "<img src=\"" . $image_name . "\" " . $sizes . " alt=\"Get Image Width And Height Example\" />";
?>

Download the PHP script above, it includes the jpg image (Desert.jpg) for your testing.

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com