How to identify contents of a byte[] is a JPEG?

From wikipedia:

JPEG image files begin with FF D8 and end with FF D9.

http://en.wikipedia.org/wiki/Magic_number_(programming)


Another source of "knowledge" about magic numbers (including for JPEG files) is the magic file used by the GNU/Linux file command.

If you have the file command installed, then file --version will tell you where the magic file lives, and you can read it using a text editor ... and careful reading of man 5 magic.

(And the magic file contents confirm the details of other answers.)


Some Extra info about other file format with jpeg: initial of file contains these bytes

BMP : 42 4D
JPG : FF D8 FF EO ( Starting 2 Byte will always be same)
PNG : 89 50 4E 47
GIF : 47 49 46 38

When a JPG file uses JFIF or EXIF, The signature is different :

Raw  : FF D8 FF DB  
JFIF : FF D8 FF E0  
EXIF : FF D8 FF E1

some code:

private static Boolean isJPEG(File filename) throws Exception {
    DataInputStream ins = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
    try {
        if (ins.readInt() == 0xffd8ffe0) {
            return true;
        } else {
            return false;

        }
    } finally {
        ins.close();
    }
}

Quoting this wikipedia article:

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.

Tags:

Java

Image

Jpeg