我有一个byte[]
我通过电线得到的,并想验证它是 JPEG。如何才能做到这一点?
本质上,不必写出文件,我或多或少想做file
命令的作用:
$ file aoeu.jpeg
aoeu.jpeg: JPEG image data, JFIF standard 1.02
我有一个byte[]
我通过电线得到的,并想验证它是 JPEG。如何才能做到这一点?
本质上,不必写出文件,我或多或少想做file
命令的作用:
$ file aoeu.jpeg
aoeu.jpeg: JPEG image data, JFIF standard 1.02
您可以读取流的第一个和最后一个字节,并检查“幻数”
基本上,幻数是标识文件内容的字节头
JPEG image files begin with FF D8 and end with FF D9.
更多信息在这里
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.
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.