14

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

3

3 Answers 3

32

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.");
}
1
  • 2
    I think this is the right approach but it's no error free. Take a look to this. In this case ImageIO couldn't read image files even when those files actually were images.
    – dic19
    Aug 13, 2013 at 12:07
5

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.

2
  • Brent Worden was faster. But you are right :) Aug 13, 2013 at 12:01
  • that is why I voted up both answers and accepted his answer ^^
    – Alaa
    Aug 13, 2013 at 17:28
1

Use this to get the extension:

String extension = "";

int i = fileName.lastIndexOf('.');
if (i > 0) {
    extension = fileName.substring(i+1);
}

And check the conditions as u want

if(extension=="jpg"){
//your code
}

and so on

7
  • 5
    What if i change the extension of an image from .jpeg to .mpeg? Aug 13, 2013 at 11:56
  • I am not sure this will always works. An extension can be changed or can be absent. Aug 13, 2013 at 11:56
  • 1
    What if there is no extension at all? Shouldn't that cause a problem here? As far as I know, the correct way is to check for the mime type. Aug 13, 2013 at 11:56
  • 2
    Usually images do not a have extensions like .mpeg or .wmv Aug 13, 2013 at 11:58
  • 2
    Use extension.equals("") instead of ==. see this question: How do I compare strings in Java?.
    – Azad
    Aug 13, 2013 at 12:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.