Get an image size with PHP

Posted in PHP -

PHP has a function called getimagesize() for getting the width and height from an image. I'm always forgetting the name of the getimagesize() function so I decided to write a post about it and showing some examples and that way maybe I'll remember in the future...

getimagesize() is one of those classic PHP functions which illustrates how bad the naming convention for PHP functions is. Usually words if function names in PHP are separate by and underscore (e.g. it would be get_image_size()) but this is one of those functions that doesn't. Anyway, I digress...

Pass getimagesize() a filename and it will return an array containing the image's width, height, what type of image it is, a text value with the width and height which can be placed directly into an <img> tag and some other stuff detailed below.

For example, if we had a JPEG image called "my-great-photo.jpg" and it was 300 pixels width and 200 pixels high, you could get the image information from it like so:

$info = getimagesize("my-great-photo.jpg");

Doing print_r($info) would return this, for the above example:

    [0] => 300
    [1] => 200
    [2] => 2
    [3] => width="300" height="200"
    [bits] => 8
    [channels] => 3
    [mime] => image/jpeg

The value in index 0 is the width.

The value in index 1 is the height.

The value in index 2 is one of the IMAGETYPE_XXX constants, such as IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG and IMAGETYPE_BMP.

The value in index 3 is the text string that can be add into an <img> tag.

The 'bits' value indicates the number of bits for each color.

The 'channels' value is either 3 for RGB or 4 for CMYK.

The 'mime' value is the image's mime type and can be used in an HTTP Content-type header.

If the file cannot be opened or parsed, the getimagesize() function will return false. If accessing the filename  image is impossible, or if it isn't a valid picture, getimagesize() will generate an error of level E_WARNING. On read error, getimagesize() will generate an error of level E_NOTICE.

Related posts: