Addev
Addev

Reputation: 32263

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

Upvotes: 7

Views: 7530

Answers (4)

Van Tung
Van Tung

Reputation: 49

You can try this code to check more accurately.

  public static boolean isImageFile(String path) {
        String mimeType = URLConnection.guessContentTypeFromName(path);
        boolean b = mimeType != null && mimeType.startsWith("image");
         if(b){
             return BitmapFactory.decodeFile(path) != null;
         }

        return false;
    }

Upvotes: 2

Logan Guo
Logan Guo

Reputation: 886

try this code segment

public static boolean isViewableImage(String name) {
    String suffix = name.substring(name.lastIndexOf('.') + 1).toLowerCase();
    if (suffix.length() == 0)
        return false;
    if (suffix.equals("svg"))
        // don't support svg preview
        return false;

    String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix);
    if (mime == null)
        return false;
    return mime.contains("image");
}

Upvotes: -2

danik
danik

Reputation: 856

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

Upvotes: 21

Perception
Perception

Reputation: 80633

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?

Upvotes: 2

Related Questions