ImageIO.read illegal argument exception - raster bands/colour space components?

后端 未结 3 739
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 20:11

Apologies for the somewhat vague title, I can\'t work out what the keywords are here. The setup\'s quite simple, I\'m opening an image with

ImageIO.read(new          


        
3条回答
  •  臣服心动
    2020-12-14 20:47

    So I was having this same issue and found that the image was gray-scale and that the default ImageIO.read implementation was not figuring that out because the image metadata wasn't quite as expected. I wrote a work around that retries the load as 'BufferedImage.TYPE_BYTE_GRAY' if it fails the main load.

                Iterator iter = ImageIO.getImageReaders(stream);
    
            Exception lastException = null;
            while (iter.hasNext()) {
                ImageReader reader = null;
                try {
                    reader = (ImageReader)iter.next();
                    ImageReadParam param = reader.getDefaultReadParam();
                    reader.setInput(stream, true, true);
                    Iterator imageTypes = reader.getImageTypes(0);
                    while (imageTypes.hasNext()) {
                        ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
                        int bufferedImageType = imageTypeSpecifier.getBufferedImageType();
                        if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) {
                            param.setDestinationType(imageTypeSpecifier);
                            break;
                        }
                    }
                    bufferedImage = reader.read(0, param);
                    if (null != bufferedImage) break;
                } catch (Exception e) {
                    lastException = e;
                } finally {
                    if (null != reader) reader.dispose();               
                }
            }
            // If you don't have an image at the end of all readers
            if (null == bufferedImage) {
                if (null != lastException) {
                    throw lastException;
                }
            }
    

提交回复
热议问题