为什么需要这样做?
因为仅仅通过后缀名我们并不能得知用户是否把图片的类型更改为其他类型.
public enum ImageType { PNG('P','N','G','-',"PNG"), JPG('J','F','I','F',"JPG"), GIF('G','I','F','-',"GIF"); private char begin, mid, end, last; private String type; private ImageType(char begin, char mid, char end, char last, String type){ this.begin = begin; this.mid = mid; this.end = end; this.last = last; this.type = type; } /** * 获取图片类型 * @param data * @return */ public static ImageType getImageType(byte[] data) { // Png: if (PNG.getBegin() == data[1] && PNG.getMid() == data[2] && PNG.getEnd() == data[3]) { return PNG; } // Gif: if (GIF.getBegin() == data[0] && GIF.getMid() == data[1] && GIF.getEnd() == data[2]) { return GIF; } // JPG: if (JPG.getBegin() == data[6] && JPG.getMid() == data[7] && JPG.getEnd() == data[8] && JPG.getLast() == data[9]) { return JPG; } return null; } }
//把JPG图片的后缀改成txt
public static void main(String[] args) throws Exception {
FileInputStream fs = new FileInputStream("d:\\Koala.txt");
byte[] data = new byte[10];//读10个长度就够了
fs.read(data);
System.out.println(ImageType.getImageType(data));
fs.close();
}
控制台依然输出:
JPG
改进:因为文件流的前10个位置是保存的文件类型的信息根据这个规律:
public enum FileType2 { FILE; private static final Map<String, String> FILE_TYPES; static { FILE_TYPES = new HashMap<String, String>(); FILE_TYPES.put("PNG", "PNG"); FILE_TYPES.put("JFIF", "JPG"); FILE_TYPES.put("GIF", "GIF"); FILE_TYPES.put("PDF", "PDF"); } /** * 从集合中取得相应类型 * * @param target * @return */ public static String getType(String target) { if (isEmpty(target)) { return null; } String result = null; for (String key : FILE_TYPES.keySet()) { if (!contains(target, key)) continue; result = FILE_TYPES.get(key); break; } return result; } /** * 是否包含 * * @param str * @param searchStr * @return */ private static boolean contains(String str, String searchStr) { if (str == null || searchStr == null) { return false; } return str.indexOf(searchStr) >= 0; } /** * 是否为空 * * @param str * @return */ private static boolean isEmpty(String str) { return str == null || str.length() == 0; } }
测试:
FileInputStream fs = new FileInputStream("d:\\Koala.JPG"); byte[] data = new byte[10];// 读10个长度就够了 fs.read(data); StringBuilder str = new StringBuilder(""); for (int i = 0; i < data.length; i++) { str.append((char) data[i]); // System.out.println(i + ":" + (char) data[i]); } System.out.println("------------------"); System.out.println(FileType2.getType(str.toString())); // System.out.println("文件类型:"+ImageType.getImageType(data).getType()); fs.close();