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


I've always used it like this:

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


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:

    [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:

    [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) {
        imagejpeg($smallImage, $event_image_path . $small_filename);
        imagegif($smallImage, $event_image_path . $small_filename);
        imagepng($smallImage, $event_image_path . $small_filename);
        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.

file descriptor ,image manipulation ,php

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}