Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Detect whether a file is PNG or JPEG

Tags:

c++

image

png

jpeg

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.

like image 368
Yippie-Ki-Yay Avatar asked Sep 22 '10 15:09

Yippie-Ki-Yay


People also ask

How can you tell if a file is PNG or JPEG?

If you are having trouble and want to check if you photo is a JPEG, look at the writing under the photo in its file name. If it ends . jpg or . jpeg- then the file is a JPEG and will upload.

How do you check if a file is a PNG in C?

Libpng provides a simple check to see if a file is a PNG file. To use it, pass in the first 1 to 8 bytes of the file to the function png_sig_cmp(), and it will return 0 if the bytes match the corresponding bytes of the PNG signature, or nonzero otherwise.

How do I check if a JPG is valid?

Confirm that the number of bytes collected matches the value of the first two bytes. The header length is usually 16. If the length between ff c0 || ff c2 and ff c4 || ff db || ff dd does not match the value of the first two bytes, or if no such byte sequence is found, then its not a valid JPEG.

Is PNG or jog better?

The biggest advantage of PNG over JPEG is that the compression is lossless, meaning there is no loss in quality each time it is opened and saved again. PNG also handles detailed, high-contrast images well.


1 Answers

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

like image 128
Tim Yates Avatar answered Sep 23 '22 05:09

Tim Yates