I want to check if the file passed is an image and if not I want to show a message indicating that the file is not an image .
try{
Image img = ImageIO.read(new File(name));
}catch(IOException ex)
{
valid=false;
System.out.println("The file" + name + "could not be opened, it is not an image");
}
When the file (referenced by name
) is not an image valid is not set to false
, why is this happening?
Should I change the type of the exception? I have read about the try-catch, and as I understand if ImageIO.read fails and the type of the exception is IOException contents of catch block will be executed. So why its not executed ?
Is there is any other way to check if the file is an image??
The Google picture search is the most widely used image search engine due to its extensive database that contains billions of images uploaded over the web. It is best to use image search Google when your aim is to find identical pictures against your queried image.
Does Windows 10 have a built-in duplicate file finder app? No, Windows 10 doesn't have a built-in file finder. But, you can do this manually through the Windows photos app. You can also download duplicate file remover and run it.
Find and Remove Duplicate Photos in 3 Easy StepsOpen Duplicate Photo Cleaner and drag some folders to the scan area. You can connect your camera or phone to add it to the scan too. Launch the scan and sit back while Duplicate Photo Cleaner looks for duplicate and similar photos. The scan won't take long.
According to the Javadocs, read returns null
if the file can not be read as an image.
If no registered ImageReader claims to be able to read the resulting stream,
null
is returned.
So, your code should be the following:
try {
Image image = ImageIO.read(new File(name));
if (image == null) {
valid = false;
System.out.println("The file"+name+"could not be opened , it is not an image");
}
} catch(IOException ex) {
valid = false;
System.out.println("The file"+name+"could not be opened , an error occurred.");
}
According to API ImageIO.read(...)
returns null
if no registered ImageReader
able to read the specified file is found, so you can simply test returned result for null
.
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