嘿所有,
每当我尝试使用ImageInputStream
获取ImageIO.createImageInputStream
对象时,它只返回null
,没有例外,警告或错误。我尝试将不同的数据类型传递给函数,一个简单的File
和一个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;
}
答案 0 :(得分:3)
你为什么要这样做? 你可以这样做:
image = ImageIO.read(source);
否Iterators
,ImageInputStreams
......一无所获!
编辑:由于您坚持认为,您的代码无效,因为您向File
发送ImageIO.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);