Given a file path what is the easiest way of know if that file is a image (of any kind) in Java(Android)? Thanks
Asked
Active
Viewed 7,305 times
4 Answers
19
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;
}

danik
- 796
- 9
- 17
-
1@MicroR , if you set `options.inJustDecodeBounds = true;` than `BitmapFactory` will not decode whole image's data, but only image's metadata. If file is valid image than `BitmapFactory` will parse metadata and fill `options.outWidth` and `options.outHeight`. These fields will contain width and height of image. If decoding error occur fields will contain -1. See docs http://developer.android.com/intl/ru/reference/android/graphics/BitmapFactory.Options.html#outWidth – danik Apr 05 '16 at 07:43
2
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;
}

Van Tung
- 49
- 1
- 3
2
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:
How to check a uploaded file whether it is a image or other file?

Community
- 1
- 1

Perception
- 79,279
- 19
- 185
- 195
-
This is *very very bad* in terms of memory and a lot of images would be checked. This can easily cause **OutOfMemoryError** – FindOut_Quran Nov 03 '15 at 04:25
-2
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");
}

Logan Guo
- 865
- 4
- 17
- 35