5

大家好,每当我尝试使用它来获取ImageInputStream对象时,ImageIO.createImageInputStream它都会返回null,没有异常、警告或错误。我尝试将不同的数据类型传递给函数,a simpleFile和 an InputStream,但都返回了null。文档说,如果没有ImageInputStreamSpi找到合适的,那么该函数将返回null,但该文件是沼泽标准 JPEG,并且 Java 肯定带有开箱即用的这种格式的服务提供商吗?谢谢你的时间。

/**
 * Reads in an image from a file and returns the image in a
 * {@code BufferedImage} object.
 *
 * @param source the file to create the {@code BufferedImage}
 * from.
 * @return the {@code BufferedImage} object representing the image
 * in {@code source}.
 */
private BufferedImage readImage( File source ) {
    // There is only one image in this file
    final int imageIndex = 0;
    BufferedImage image = null;

    try {
        // Get the ImageReader object for this filetype
        Iterator readers =
            ImageIO.getImageReaders( source );
        ImageReader reader = (ImageReader) readers.next();

        // Create an ImageInputStream object from the source image file
        ImageInputStream iis = ImageIO.createImageInputStream( source );
        // Raises IllegalArgumentException, because iis is null
        reader.setInput( iis, true );

        // Read the image file
        image = reader.read( imageIndex );
    } catch ( Exception exception ) {
        exception.printStackTrace();
        System.exit( -1 );
    }

    return image;
}
4

1 回答 1

3

你为什么要这么做??你可以简单地这样做:

image = ImageIO.read(source);

IteratorsImageInputStreams……什么都没有!

编辑:由于您坚持,您的代码无法正常工作,因为您发送的是FiletoImageIO.getImageReaders()而不是ImageInputStream. 所以你的代码应该是这样的:

ImageInputStream iis = ImageIO.createImageInputStream(source);
Iterator readers = ImageIO.getImageReaders(iis);
ImageReader reader = (ImageReader) readers.next();

reader.setInput(iis, false);
image = reader.read(imageIndex);
于 2011-02-27T02:13:52.093 回答