Getting an image's MIME type

string image_type_to_mime_type ( int imagetype)

So far we have been hand-crafting the header() function call in each of the image scripts, but many people find MIME types hard to remember and/or clumsy to use. If you fit into this category, you should be using the image_type_to_mime_type() function, as it takes a constant as its only parameter and returns the MIME type string. For example, passing in IMAGETYPE_GIF will get you back image/gif, passing in IMAGETYPE_JPEG will get you back image/jpeg, and passing in IMAGETYPE_PNG will get you back image/png.

If these constants sounds as hard to remember as the MIME types, you're probably right. However, a while back we looked at the getimagesize() function, and I mentioned that the third element in the array returned by that function is the type of file it is. These two functions both use the same constant, which means you can use getimagesize() and pass the third element into image_type_to_mime_type() to have it get the appropriate MIME type for your image - no memorisation of constants required.

    $info = getimagesize("button.png");
    print image_type_to_mime_type($info[2]);


If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Keeping your files small >>

Previous chapter: Interlacing an image

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.