Reputation: 32263
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
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
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
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
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:
How to check a uploaded file whether it is a image or other file?
Upvotes: 2