Search code examples
javaimageiteratorimage-formats

Exception while reading image ==java.lang.IllegalArgumentException: image == null


I am reading a image and want to get the image format.

private static String getFormatName(Object o) {
try {
    // Create an image input stream on the image
    ImageInputStream iis = ImageIO.createImageInputStream(o);

    // Find all image readers that recognize the image format
    Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
    if (!iter.hasNext()) {
        // No readers found
        return null;
    }

    // Use the first reader
    ImageReader reader = (ImageReader)iter.next();

    String name = reader.getFormatName();
    iis.close();
    return name;
} catch (IOException e) {
}
// The image could not be read
return null;

}

when I execute it I am getting the following exception,

java.lang.IllegalArgumentException: image == null!

Solution

  • You are Closing the stream, before the reader gets the chance to read the format..

    So the sequence of statements are:

    reader.getFormatName();
    iis.close();
    return name;