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

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
Alaa
  • 539
  • 3
  • 8
  • 29

3 Answers3

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.");
}
KlimczakM
  • 12,576
  • 11
  • 64
  • 83
Brent Worden
  • 10,624
  • 7
  • 52
  • 57
  • 2
    I think this is the right approach but it's no error free. Take a look to [this](http://stackoverflow.com/questions/18079754/convert-and-display-image-from-byte-array?noredirect=1#comment26495118_18079754). In this case `ImageIO` couldn't read image files even when those files actually were images. – dic19 Aug 13 '13 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.

MWiesner
  • 8,868
  • 11
  • 36
  • 70
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
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

MWiesner
  • 8,868
  • 11
  • 36
  • 70
Hybrid Developer
  • 2,320
  • 1
  • 34
  • 55