Domanda

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!
È stato utile?

Soluzione

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;

Altri suggerimenti

Updated: You also need to call setInput()

You can't close the stream. When you do how is the reader going to read the image? Do the following:

reader.setInput(iis);
String name = reader.getFormatName();
iis.close();
return name;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top