爲何須要這樣作?java
由於僅僅經過後綴名咱們並不能得知用戶是否把圖片的類型更改成其餘類型.app
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個位置是保存的文件類型的信息根據這個規律: ui
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; } }測試:this
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();