java 自動識別圖片檔案類型 圖片尾碼 圖片類型

來源:互聯網
上載者:User

 

檔案類型識別的方法有很多,如使用URLConnection對象的getContentType方法獲得:

File file = new File(“檔案路徑”);String type = file.toURL().openConnection().getContentType();

其他方法可參考資料:http://www.rgagnon.com/javadetails/java-0487.html中介紹的方法針對不同形式的資料進行解析。

若資料是位元組數組時,可參考程式:

/**  * 根據圖片的bits位元組數組中的資料,識別圖片檔案類型,再根據prefix內容構造一個適當的檔案名稱  * @param bits 圖片位元組數組  * @param prefix 用於構造檔案名稱的首碼串  * @return 0元素存放檔案名稱,1元素存放檔案類型  */ public static String [] imgBitsDeal(byte[]bits, String prefix){ String [] rt = new String[2];// snippet for JMimeMagic lib// http://sourceforge.net/projects/jmimemagic/Magic parser = new Magic() ;MagicMatch match = null;try {match = parser.getMagicMatch(bits);rt[1] = match.getMimeType();//檔案類型rt[0] = prefix + "." + match.getExtension();//構造檔案名稱(含副檔名)//System.out.println(match.getMimeType()) ;//System.out.println(match.getExtension()) ;} catch (Exception e) {// TODO Auto-generated catch blockrt[0] = prefix + "." + "png";//預設檔案名稱rt[1] = "image/png";//預設檔案類型e.printStackTrace();} return rt; }

 下載包地址: http://download.csdn.net/source/3551651
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.