Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Know if a file is a image in Java/Android

Given a file path what is the easiest way of know if that file is a image (of any kind) in Java(Android)? Thanks

like image 794
Addev Avatar asked Feb 11 '12 22:02

Addev


2 Answers

public static boolean isImage(File file) {
    if (file == null || !file.exists()) {
        return false;
    }
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(file.getPath(), options);
    return options.outWidth != -1 && options.outHeight != -1;
}
like image 101
danik Avatar answered Sep 28 '22 10:09

danik


There are external tools that can help you do this. Check out JMimeMagic and JMagick. You can also attempt to read the file using the ImageIO class, but that can be costly and is not entirely foolproof.

BufferedImage image = ImageIO.read(new FileInputStream(new File(..._)));

This question has been asked on SO a couple of times. See these additional threads on the same topic:

Check if a file is an image

How to check a uploaded file whether it is a image or other file?

like image 37
Perception Avatar answered Sep 28 '22 10:09

Perception