Given a file path what is the easiest way of know if that file is a image (of any kind) in Java(Android)? Thanks
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;
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With