最近需要对网络图片和本地图片格式是否为gif格式进行判定。
本地图片的判定,一开始使用文件名后缀直接判定,发现这根本不能正确的识别图片的真正格式。如果程序保存图片写死图片文件后缀,那么文件名后缀和系统相册数据库的mimeType字段,都会是写死的,不能真正表示图片的格式。
方法一:通过BitmapFactory.Options获取
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(localPath, options);
String type = options.outMimeType;
LogUtil.d("isGif imagType -> " + type);
方法二:通过文件编码格式判定
gif的文件编码格式,可以参考
http://blog.csdn.net/wzy198852/article/details/17266507
private static boolean isGif(String localPath) {
try {
FileInputStream inputStream = new FileInputStream(localPath);
int[] flags = new int[5];
flags[0] = inputStream.read();
flags[1] = inputStream.read();
flags[2] = inputStream.read();
flags[3] = inputStream.read();
inputStream.skip(inputStream.available() - 1);
flags[4] = inputStream.read();
inputStream.close();
return flags[0] == 71 && flags[1] == 73 && flags[2] == 70 && flags[3] == 56 && flags[4] == 0x3B;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
同理jpg识别方法为:
private boolean isJpgFile(File file) {
try {
FileInputStream bin = new FileInputStream(file);
int b[] = new int[4];
b[0] = bin.read();
b[1] = bin.read();
bin.skip(bin.available() - 2);
b[2] = bin.read();
b[3] = bin.read();
bin.close();
return b[0] == 255 && b[1] == 216 && b[2] == 255 && b[3] == 217;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
参考链接:
https://blog.csdn.net/kehengqun1/article/details/49252549
https://blog.csdn.net/zhuwentao2150/article/details/51793828
https://blog.csdn.net/wzy198852/article/details/17266507
网友评论