import java.io.File; import java.io.IOException; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; public class ImageDemo { /** * @param args */ public static void main(String[] args) { File file = new File("E:/download_test/pics/1c/1cd5v0uya36wg0rf4fu39dtym.png"); boolean result = isImage(file); System.out.println("result="+result); getExtension(file); } public static void getExtension(File file) { ImageInputStream iis = null; try { iis = ImageIO.createImageInputStream(file); Iterator<ImageReader> iter = ImageIO.getImageReaders(iis); if(iter.hasNext()){ System.out.println("扩展名:"+iter.next().getFormatName()); } } catch (IOException e) { e.printStackTrace(); }finally{ if(iis!=null){ try { iis.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static boolean isImage(File resFile){ ImageInputStream iis = null; try { iis = ImageIO.createImageInputStream(resFile); Iterator<ImageReader> iter = ImageIO.getImageReaders(iis); if (iter.hasNext()) {//文件不是图片 return true; } } catch (IOException e) { e.printStackTrace(); }finally{ if(iis!=null){ try { iis.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; } }
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10547.html