Using PHP to get the dimensions of an image

The following code will get the dimensions of an image:

list($width, $height, $type, $attr) = getimagesize(PATH_TO_IMAGE);

I found this useful when using a lightbox to load an image that I didn't initially know the size of, to ensure the lightbox positioned itself in the middle, based on the height and width of the image.

The contents of $attr is useful for slotting straight into an <img> tag, like so:

<img src="URL" <?php echo $attr?> />

This will produce, for example:

<img src="URL" width="200" height="300">

View this post on Gitlab

You might also enjoy…

  • Giving something a 'Last' Class

    Posted on 14th February 2011.

    If you want to apply a different class to the last item in a list generated by PHP, start off with Setting the $lastOne variable to the end of your list

  • Creating a HTML Email

    Posted on 17th November 2010.

    Creating a HTML email is like going back to the nineties with web design – you have to go against all your natural instincts as a web designer.

Mike Street

Written by Mike Street

Mike is a front-end developer from Brighton, UK. He spends his time writing, cycling and coding. You can find Mike on Twitter.