Android: How to check if file is image?-ThrowExceptions

Exception or error:

Possible Duplicate:
Know if a file is a image in Java/Android

How can I check a file if it is an image?
like following:

if(file.isImage)….

If it’s not possible with standard libraries, how can I do it with the MagickImage lib?

Thanks in advance!

How to solve:

Try this code.

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

}

It’ll work fine.

Use this like
new ImageFileFilter(pass file name);

###

I think if you want to check whether a file is an image, you need to read it. An image file may not obey the file extension rules. You can try to parse the file by BitmapFactory as following:

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

Leave a Reply

Your email address will not be published. Required fields are marked *