简体   繁体   中英

Detecting image encoding in Java

I'm accepting an image as input from the user. I want to only allow a JPEG image. The image is arriving as an InputStream (called myInputStream below). In the code below, the Iterator returned by ImageIO.getImageReaders() is always empty.

ImageInputStream imageInputStream = ImageIO.createImageInputStream(
    myInputStream);
Iterator<ImageReader> iter = ImageIO.getImageReaders(imageInputStream);
if (!iter.hasNext()) {
    // this always happens
}
ImageReader reader = (ImageReader) iter.next();
if (!reader.getFormatName().equals("jpeg")) {
    // haven't got this far yet
}

I have also tried passing myInputStream directly to ImageIO.getImageReaders() with the same result.

An empty iterator usually means ImageIO hasn't found a good image reader for decoding your image. This may be because you'are missing the right decoder in your classpath , or you image has an unsupported color model .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM