Hudzilla.org - the homepage of Paul Hudson
Contents > Multimedia > Images Wish List | Report Bug | About Me ]

11.2.28     Getting an image's MIME type: image_type_to_mime_type()

This is NOT the latest copy of this book; click here for the latest version.

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.

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




<< 11.2.27 Interlacing an image: imageinterlace()   11.2.29 Keeping your files small >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Dan Finnie - 29 Aug 2008

It looks like you don't even have to use the above function, $info['mime'] will do the same thing.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is seven plus one?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow