知道文件是否是Java / Android中的图像

给定一个文件路径,知道该文件是否是Java(Android)中的图像(任何类型)的最简单方法是什么? 谢谢

有一些外部工具可以帮助您做到这一点。 查看JMimeMagic和JMagick 。 您也可以尝试使用ImageIO类读取文件,但这可能代价高昂且并非完全万无一失。

 BufferedImage image = ImageIO.read(new FileInputStream(new File(..._))); 

这个问题已被问过几次了。 请参阅相同主题的其他主题:

检查文件是否是图像

如何检查上传的文件是图像还是其他文件?

 public static boolean isImage(File file) { if (file == null || !file.exists()) { return false; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getPath(), options); return options.outWidth != -1 && options.outHeight != -1; } 

试试这段代码

 public static boolean isViewableImage(String name) { String suffix = name.substring(name.lastIndexOf('.') + 1).toLowerCase(); if (suffix.length() == 0) return false; if (suffix.equals("svg")) // don't support svg preview return false; String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix); if (mime == null) return false; return mime.contains("image"); }