Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the file is an image [duplicate]

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??

like image 216
Alaa Avatar asked Aug 13 '13 11:08

Alaa


People also ask

How do you identify identical images?

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 duplicate photo finder?

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.

How can I find duplicate files in JPEG?

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.


2 Answers

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.");
}
like image 70
Brent Worden Avatar answered Oct 13 '22 03:10

Brent Worden


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.

like image 41
Evgeniy Dorofeev Avatar answered Oct 13 '22 03:10

Evgeniy Dorofeev