本文介绍了ImageIO.createImageInputStream 不断返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

大家好,每当我尝试使用 ImageIO.createImageInputStream 获取 ImageInputStream 对象时,它只会返回 null 而没有异常、警告或错误.我尝试将不同的数据类型传递给函数,一个简单的 File 和一个 InputStream,但都返回了 null.文档说,如果没有找到合适的 ImageInputStreamSpi 则该函数将返回 null,但该文件是沼泽标准的 JPEG,当然 Java 附带了一个服务提供者这种开箱即用的格式?感谢您抽出宝贵时间.

Hey all,Whenever I try to get an ImageInputStream object using ImageIO.createImageInputStream it simply returns null with no exceptions, warnings or errors. I have tried passing different data types to the function, a simple File, and an InputStream, but both returned null also. The documentation says that if no suitable ImageInputStreamSpi is found then the function will return null, but the file is a bog-standard JPEG, and surely Java comes with a service provider for such a format out of the box?Thanks for your time.

/**
 * 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;
}

推荐答案

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

Why are you doing all that??you can simply do this:

image = ImageIO.read(source);

没有 IteratorsImageInputStreams...什么都没有!

No Iterators, ImageInputStreams... no nothing !

EDIT:既然你坚持,你的代码不起作用,因为你发送一个 FileImageIO.getImageReaders() 而不是一个 ImageInputStream.所以你的代码应该是这样的:

EDIT: Since you insist, your code is not working because you're sending a File to ImageIO.getImageReaders() instead of a ImageInputStream. SO your code should look something like that:

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

reader.setInput(iis, false);
image = reader.read(imageIndex);

这篇关于ImageIO.createImageInputStream 不断返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 14:46