Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Determining the Image Type of a File

DZone's Guide to

Determining the Image Type of a File

Who would've thought that a function to get the size of an image would tell you so much more?

· Web Dev Zone ·
Free Resource

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

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 useimagejpeg, 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.

Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

Topics:
php ,image manipulation ,file descriptor

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}