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

时间:2012-12-07 09:29:01

标签: android image listview imagemagick

  

可能重复:
  Know if a file is a image in Java/Android

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

如果(file.isImage)......

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

提前致谢!

2 个答案:

答案 0 :(得分:45)

我认为如果你想检查文件是否是图像,你需要阅读它。图像文件可能不遵守文件扩展名规则。您可以尝试按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.
}

答案 1 :(得分:19)

亲爱的尝试此代码。

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;         
        }

    }

它很好。

并使用此类似 (新的ImageFileFilter(传递文件名));

相关问题