将字节数组转换为 Java 中的图像 - 不知道类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1212882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Byte Array to image in Java - without knowing the type
提问by PHeath
Sounds simple right? Use
听起来很简单吧?用
ImageIO.read(new ByteArrayInputStream(bytes));
Here's the wrinkle. For some reason it is detecting a jpeg as a bmp, and that is the first ImageReader returned when I call
这是皱纹。出于某种原因,它将 jpeg 检测为 bmp,这是我调用时返回的第一个 ImageReader
ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes));
Iterator<ImageReader> readers=ImageIO.getImageReaders(iis);
This causes the image to come out corrupted. Is there a way to tell through java short of looking directly at the bytes for the header, and failing that does anyone know of a good reference for the byte headers for the different images?
这会导致图像损坏。有没有办法通过 java 直接查看头的字节来判断,如果失败,有没有人知道不同图像的字节头的良好参考?
Just letting you guys know I am still working on this. I'll let you know if/when I have an answer. I thank all of you for your responses so far.
只是让你们知道我仍在努力。如果/当我有答案时,我会通知您。到目前为止,我感谢你们所有人的回应。
回答by jedierikb
Haven't played with ImageIO in a awhile, and have not tested this, but I seem to recall something like this working. (since you say you know your file is a jpg and not a bitmap, I am using that information to help find the right loader).
有一段时间没玩过 ImageIO,也没有测试过,但我似乎记得这样的工作。(因为您说您知道您的文件是 jpg 而不是位图,我正在使用该信息来帮助找到正确的加载程序)。
String inFormat = "jpg";
Iterator inReaders = ImageIO.getImageReadersByFormatName(inFormat);
...
nextInReader.setInput( iis );
回答by mic.sca
For the reference you can have a look at wikipedia, you can find the header of the different formats there.
http://en.wikipedia.org/wiki/Graphics_Interchange_Format
http://en.wikipedia.org/wiki/BMP_file_format
http://en.wikipedia.org/wiki/JPEG
对于参考,您可以查看维基百科,您可以在那里找到不同格式的标题。
http://en.wikipedia.org/wiki/Graphics_Interchange_Format
http://en.wikipedia.org/wiki/BMP_file_format
http://en.wikipedia.org/wiki/JPEG
回答by Michael Borgwardt
Is the BMP reader the onlyone returned by getImageReaders()
? Maybe you get more than one and can make a choice based on that.
BMP 阅读器是唯一返回的getImageReaders()
吗?也许您会得到不止一个,并且可以基于此做出选择。