C ++ - determine if a PNG or JPEG file

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

I am sure there is some way, and these files probably have their own signatures, and there is some way to distinguish them.

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

+6
c ++ image png jpeg
source share
4 answers

In addition to Tim Yates’s suggestion to read the magic number manually, 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 need a type, you can try to read only the sizes , and not download the entire file.

+2
source share

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

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

PNG image files begin with an 8-byte signature that identifies the file as a PNG file and allows you to detect common file transfer problems: \ 211 PNG \ r \ n \ 032 \ n

+17
source share

The answer to this question essentially answers the above answers, but I thought I'd add the following: if you ever need to define file types outside of just "JPEG, PNG, other", always libmagic . This is what the useful Unix file really makes, which is really quite magical on many modern operating systems.

+3
source share

Image file types, such as PNG and JPG, have well-defined file formats that include signatures that identify them. All you have to do is read enough file to read this signature.

Signed signatures are well documented:

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

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

+1
source share

All Articles