【发布时间】:2012-03-03 22:07:09
【问题描述】:
给定一个文件路径,知道该文件是否是 Java(Android) 中的图像(任何类型)的最简单方法是什么?谢谢
【问题讨论】:
给定一个文件路径,知道该文件是否是 Java(Android) 中的图像(任何类型)的最简单方法是什么?谢谢
【问题讨论】:
您可以尝试使用此代码进行更准确的检查。
public static boolean isImageFile(String path) {
String mimeType = URLConnection.guessContentTypeFromName(path);
boolean b = mimeType != null && mimeType.startsWith("image");
if(b){
return BitmapFactory.decodeFile(path) != null;
}
return false;
}
【讨论】:
试试这个代码段
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");
}
【讨论】:
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;
}
【讨论】:
options.inJustDecodeBounds = true; 比 BitmapFactory 将不会解码整个图像的数据,而只会解码图像的元数据。如果文件是有效图像,则BitmapFactory 将解析元数据并填充options.outWidth 和options.outHeight。这些字段将包含图像的宽度和高度。如果发生解码错误,字段将包含 -1。请参阅文档developer.android.com/intl/ru/reference/android/graphics/…
有一些外部工具可以帮助您做到这一点。查看JMimeMagic 和JMagick。您也可以尝试使用 ImageIO 类读取文件,但这可能代价高昂且并非完全万无一失。
BufferedImage image = ImageIO.read(new FileInputStream(new File(..._)));
这个问题已经在 SO 上被问过几次了。请参阅有关同一主题的这些附加主题:
How to check a uploaded file whether it is a image or other file?
【讨论】: