1

I have a byte[] that I got through the wire and want to verify that it's a JPEG. How can this be done?

Essentially, without having to write out a file, I'd like to do, more-or-less, what the file command does:

$ file aoeu.jpeg
aoeu.jpeg: JPEG image data, JFIF standard 1.02
Noel Yap
  • 18,822
  • 21
  • 92
  • 144

3 Answers3

6

You can read the first and last bytes of the stream, and check the "Magic Number"

Basically, Magic Numbers are byte headers that identify the file contents

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

More info here

A.H.
  • 63,967
  • 15
  • 92
  • 126
Cristian Meneses
  • 4,013
  • 17
  • 32
1

A JPEG image starts with FF D8 so you can check if the first 2 bytes are FF D8.

Example code:

    InputStream stream = new FileInputStream(file);

    byte[] bytes = new byte[2];

    stream.read(bytes);

    if (bytes[0] != (byte)0xFF || bytes[1] != (byte)0xD8) {
        //no jpeg
    }

    stream.close()

Of course you can't be sure that the JPEG is valid and loads correct.

maxammann
  • 1,018
  • 3
  • 11
  • 17
  • `bytes[0] != 0xFF` will always be `true`, because `0xFF` is an `int` literal representing `255`, and the maximum value in `bytes[0]` is `127`. You have the right idea, but the code is wrong. – jlordo Aug 01 '13 at 22:43
  • oh yeah give me one moment, already late here :P – maxammann Aug 01 '13 at 22:44
  • @jlordo should work now, another way would be to convert bytes[0] and bytes[1] to a unsigned byte but I think this is better – maxammann Aug 01 '13 at 22:55
0

If found this interesting comment:

Similarly, a commonly used magic number for JPEG (Joint Photographic Experts Group) image files is 0x4A464946, which is the ASCII equivalent of JFIF (JPEG File Interchange Format). However, JPEG magic numbers are not the first bytes in the file; rather, they begin with the seventh byte.

Found it here http://www.linfo.org/magic_number.html

So you could look for:

Hex: FF D8 xx xx xx xx 4A 46 49 46 00
ASCII: ÿØÿè..JFIF.
Lee Meador
  • 12,829
  • 2
  • 36
  • 42