Android:如何检查文件是否是图像?

Mar*_*eiz 18 android listview image imagemagick

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

如果文件是图像,我该如何检查?如下:

如果(file.isImage)....

如果标准库无法实现,我怎样才能使用MagickImage lib?

提前致谢!

zsx*_*ing 46

我想如果你想检查文件是否是图像,你需要阅读它.图像文件可能不遵守文件扩展名规则.您可以尝试通过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.
}
Run Code Online (Sandbox Code Playgroud)

  • options.inJustDecodeBounds = true减少解析时间成本,因为decodeFile将仅解析图像的宽度和高度. (3认同)
  • @zsxwing`decodeFile(String,Options)`如果设置`inJustDecodeBounds = true`,将**总是**返回`null`.使用此检查来查看它是否已成功解码:`if(options.outWidth!= -1 && options.outHeight!= -1)` (3认同)
  • 但你需要一个`try``catch`吧? (2认同)

Zal*_*inh 20

亲爱的,请试用此代码.

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

    public ImageFileFilter(File newfile) {
        this.file = newfile;
    }

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

}
Run Code Online (Sandbox Code Playgroud)

它很好.

和使用这就像(新的ImageFileFilter(传递文件名));

  • @ZalaJanaksinh对于任何具有"图像文件扩展名"的文件,这将返回"true",例如,如果我将`test.mp3`重命名为`test.jpg`,则您的方法将返回`true`. (12认同)
  • 这工作......现在我必须搜索每个图像扩展... (5认同)