tags:

views:

73

answers:

4

Hello!

Is there any fast way to determine if some arbitrary image file is a png file or a jpeg file or none of them?

I'm pretty sure there is some way and these files probably have some sort of their own signatures and there should be some way to distinguish them.

If possible, could you also provide the names of the corresponding routines in libpng / libjpeg / boost::gil::io.

Thank you.

+7  A: 

Look at the magic number at the beginning of the file. From the Wikipedia page:

JPEG image files begin with FF D8 and end with FF D9. JPEG/JFIF files contain the ASCII code for "JFIF" (4A 46 49 46) as a null terminated string. JPEG/Exif files contain the ASCII code for "Exif" (45 78 69 66) also as a null terminated string, followed by more metadata about the file.

PNG image files begin with an 8-byte signature which identifies the file as a PNG file and allows detection of common file transfer problems: \211 P N G \r \n \032 \n

Tim Yates
+1  A: 

Image file types like PNG and JPG have well-defined file formats that include signatures identifying them. All you have to do is read enough of the file to read that signature.

The signatures you need are well documented:

http://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header

http://en.wikipedia.org/wiki/JPEG#Syntax_and_structure

aalpern
+2  A: 

Apart from Tim Yates' suggestion of reading the magic number "by hand", the Boost GIL documentation says:

  • png_read_image throws std::ios_base::failure if the file is not a valid PNG file.
  • jpeg_read_image throws std::ios_base::failure if the file is not a valid JPEG file.

Similarly for other Boost GIL routines. If you only want the type, you might want to try reading only the dimensions, rather than loading the entire file.

larsmans
+2  A: 

The question is essentially answered by the above replies, but I thought I'd add the following: If you ever need to determine file types beyond just "JPEG, PNG, other", there's always libmagic. This is what powers the Unix utility file, which is pretty magical indeed, on many of the modern operating systems.

gspr