java獲取圖片類型

/*

 File file = new File("C:/Users/zhangzhengyi/Desktop/tt1.png");
byte[] buf = new byte[10240];
 
FileInputStream fi = new FileInputStream(file);
System.out.println(fi.read(buf));
System.out.println(getContentType(buf));

*/



public static String getContentType(byte[] mapObj) throws IOException

 {
   String type = "";
   ByteArrayInputStream bais = null;
   MemoryCacheImageInputStream mcis = null;
   try {
     bais = new ByteArrayInputStream(mapObj);
     mcis = new MemoryCacheImageInputStream(bais);
     Iterator itr = ImageIO.getImageReaders(mcis);
     while (itr.hasNext()) {
       ImageReader reader = (ImageReader)itr.next();
       if (reader instanceof GIFImageReader)
         type = "image/gif";
       else if (reader instanceof JPEGImageReader)
         type = "image/jpeg";
       else if (reader instanceof PNGImageReader)
         type = "image/png";
       else if (reader instanceof BMPImageReader)
         type = "application/x-bmp";
     }
   }
   finally {
     if (bais != null)
       try {
         bais.close();
       }
       catch (IOException ioe)
       {
       }
     if (mcis != null)
       try {
         mcis.close();
       }
       catch (IOException ioe)
       {
       }
   }
   return type;
 }
發佈了85 篇原創文章 · 獲贊 16 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章