PHP Image Sizes

You might need the size of an image for many reasons – in this tutorial I’ll go over the simple task of getting this information.

The Code

<?
$info = getimagesize("image.gif");
$width = $info[0];
$height = $info[1];
$type = $info[2];
$attr = $info[3];
?>

The function getimagesize returns an array with 4 values. I’ve written the above example so you can clearly see which indexes return which information – below you can see a shorter way of getting the same result.

<?
list($width, $height, $type, $attr)
       = getimagesize("image.gif");
?>

Using the Sizes
If you want to use the output to display an image, with the correct html width and height, you can do the following..

<?
echo "<img src=\"image.gif\" width=\"$width\"".
     " height=\"$height\">";
?>

Or if you want you can use the $attr which contains the html width & height code already:

<?
echo "<img src=\"image.gif\" $attr>";
?>