Android: How to check if file is image?

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

Try this code.

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

}

It'll work fine.

Use this like new ImageFileFilter(pass file name);