Pragmatism in the real world

Determining the image type of a file

One thing I learnt recently which I probably should have known already is that getimagesize() returns more than just the width and height of the image.

I’ve always used it like this:

list($width, $height) = getimagesize($filename);

However, getimagesize() also returns up to 5 more pieces of information.

Interestingly, the data array is a mix of indexed elements and named elements For example, for a file I uploaded while testing a PR, the output of print_r(getimagesize($filename)) is:

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

A very strange decision when designing the response of this function!

Index 2 is the file type which is an “IMAGETYPE” constant, such as IMAGETYPE_PNG. Note that there’s also a constant called IMG_PNG, but this is a different number, so make sure you use the right one!

This is useful for file uploads. Consider this data in $_FILES:

Array
(
    [image] => Array
        (
            [name] => myimage
            [type] => application/octet-stream
            [tmp_name] => /tmp/phpbGyIq7
            [error] => 0
            [size] => 90410
        )

)

In this case, there is no extension on the uploaded filename and the type is application/octet-stream. If I want to resize this image using gd, then I’m going to need to know whether to use imagejpeg, imagegif or imagepng. A simple way to do this is something like this:

list($width, $height, $imageType) = getimagesize($filename);

// create $smallImage using imagecreatetruecolor() and imagecopyresampled(), etc.

// save image
switch ($imageType) {
    case IMAGETYPE_JPEG:
        imagejpeg($smallImage, $event_image_path . $small_filename);
        break;
    case IMAGETYPE_GIF:
        imagegif($smallImage, $event_image_path . $small_filename);
        break;
    case IMAGETYPE_PNG:
        imagepng($smallImage, $event_image_path . $small_filename);
        break;
    default:
        throw new Exception("Unable to deal with image type");
}

It’s easier than dealing with the type from $_FILES too and by writing it down, maybe I’ll remember it.

2 thoughts on “Determining the image type of a file

  1. How to upload your file?
    why i can't do like above.

    "`html

    "`

    "`php
    var_dump(getimagesize($_FILES['file']['name']));
    "`

Comments are closed.