23

可能重复:
知道文件是否是 Java/Android 中的图像

如果文件是图像,如何检查文件?如下所示:

如果(文件.isImage)....

如果标准库无法做到这一点,我该如何使用 MagickImage 库来做到这一点?

提前致谢!

4

2 回答 2

48

我想如果你想检查一个文件是否是一个图像,你需要阅读它。图像文件可能不遵守文件扩展名规则。您可以尝试通过BitmapFactory解析文件,如下所示:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
if (options.outWidth != -1 && options.outHeight != -1) {
    // This is an image file.
}
else {
    // This is not an image file.
}
于 2012-12-07T09:41:44.163 回答
20

试试这个代码。

public class ImageFileFilter implements FileFilter {
   
    private final String[] okFileExtensions = new String[] {
        "jpg",
        "png",
        "gif",
        "jpeg"
    };


    public boolean accept(File file) {
        for (String extension: okFileExtensions) {
            if (file.getName().toLowerCase().endsWith(extension)) {
                return true;
            }
        }
        return false;
    }

}

它会正常工作的。

像这样使用 new ImageFileFilter(pass file name);

于 2012-12-07T09:38:59.470 回答