通过文件头部字节判断文件格式
本图片验证工具类摘取自itext5的
Image类的public static Image getInstance(final URL url, boolean recoverFromImageError)方法
private boolean verifyImageFormat(InputStream imageIS) throws IOException {
//获取文件头的前8个字节
int c1 = imageIS.read();
int c2 = imageIS.read();
int c3 = imageIS.read();
int c4 = imageIS.read();
// jbig2
int c5 = imageIS.read();
int c6 = imageIS.read();
int c7 = imageIS.read();
int c8 = imageIS.read();
imageIS.close();
imageIS = null; // help GC
if (c1 == \'G\' && c2 == \'I\' && c3 == \'F\') {
//gif
return true;
}
if (c1 == 0xFF && c2 == 0xD8) {
//Jpeg
return true;
}
if (c1 == 0x00 && c2 == 0x00 && c3 == 0x00 && c4 == 0x0c) {
//Jpeg2000
return true;
}
if (c1 == 0xff && c2 == 0x4f && c3 == 0xff && c4 == 0x51) {
//Jpeg2000
return true;
}
if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1]
&& c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3]) {
//PngImage
return true;
}
if (c1 == 0xD7 && c2 == 0xCD) {
//ImgWMF
return true;
}
if (c1 == \'B\' && c2 == \'M\') {
//BmpImage
return true;
}
if (c1 == \'M\' && c2 == \'M\' && c3 == 0 && c4 == 42
|| c1 == \'I\' && c2 == \'I\' && c3 == 42 && c4 == 0) {
//TiffImage
return true;
}
if ( c1 == 0x97 && c2 == \'J\' && c3 == \'B\' && c4 == \'2\' &&
c5 == \'\r\' && c6 == \'\n\' && c7 == 0x1a && c8 == \'\n\' ) {
//JBIG2Image
return true;
}
return false;
}