我不明白为什么 bigInputStream 为空,即使数据设置得很好。
InputStream in = new ByteArrayInputStream(data);
BufferedImage bufferedImage;
bufferedImage = ImageIO.read(in);
// next instruction has problem
ImageInputStream bigInputStream = ImageIO.createImageInputStream(bufferedImage);
Iterator<ImageReader> iter = ImageIO.getImageReaders(bigInputStream);
if (!iter.hasNext()) {
// thow exception here
}
ImageReader reader = iter.next();
答案 0 :(得分:1)
这里是我在this link中找到的完美工作方法:
private static String determineImageFormat( byte[] imageBytes ) throws IOException {
final ByteArrayInputStream bStream = new ByteArrayInputStream( imageBytes );
final ImageInputStream imgStream = ImageIO.createImageInputStream( bStream );
final Iterator<ImageReader> iter = ImageIO.getImageReaders( imgStream );
final ImageReader imgReader = iter.next();
return imgReader.getFormatName();
}
可能会添加一些验证。
答案 1 :(得分:1)
为了尝试回答这个问题,有问题的一行是(正如OP指出的那样):
ImageInputStream bigInputStream = ImageIO.createImageInputStream(bufferedImage);
(小字体:理论上这可能会起作用,但它需要自定义服务提供商才能从已经加载到内存中的图像中读取图像数据,这看起来有点奇怪。)
应该是:
ImageInputStream bigInputStream = ImageIO.createImageInputStream(in);
即ImageInputStream
是ImageReader
的辅助类,用于从File
,InputStream
,FileChannel
等处读取二进制数据。这不适用于从已经构建的图像中读取数据。
在修复之后,您的代码可能如下所示:
InputStream in = new ByteArrayInputStream(data);
ImageInputStream bigInputStream = ImageIO.createImageInputStream(in);
Iterator<ImageReader> iter = ImageIO.getImageReaders(bigInputStream);
if (!iter.hasNext()) {
// thow exception here
}
ImageReader reader = iter.next();
BufferedImage bufferedImage = reader.read(0); // Read the first image in the file
// Do other tings with reader, like getting the file format
String format = reader.getFormatName();
...
reader.dispose(); // Should be done in finally block, but I leave that out