JAVA:如何从字节 [] 创建 .PNG 图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22368003/
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
JAVA : How to create .PNG image from a byte[]?
提问by MadMonkey
I have seen some code source, but I do not understand...
我看过一些代码源,但我不明白......
I use Java 7
我使用 Java 7
Please, how to convert a RGB(Red,Green,Blue) Byte Array(or something similar) to a .PNG file format?
请问,如何将 RGB(红色、绿色、蓝色)字节数组(或类似的东西)转换为 .PNG 文件格式?
Example from an array that could represent "a RGB pixel" :
来自可以表示“RGB 像素”的数组的示例:
byte[] aByteArray={0xa,0x2,0xf};
Important Aspect :
重要方面:
I try to generate a .PNG file only from a byte[] "notfrom a previous existing file"
我尝试仅从字节 [] “而不是从以前的现有文件”生成 .PNG 文件
is it possible with an existing API? ;)
是否可以使用现有的 API?;)
Here my first code :
这是我的第一个代码:
byte[] aByteArray={0xa,0x2,0xf};
ByteArrayInputStream bais = new ByteArrayInputStream(aByteArray);
File outputfile = new File("image.png");
ImageIO.write(bais, "png", outputfile);
....Error :No suitable Method Found
....错误:找不到合适的方法
Here the other version modified from Jeremybut look similar :
这里是从Jeremy修改的另一个版本,但看起来很相似:
byte[] aByteArray={0xa,0x2,0xf};
ByteArrayInputStream bais = new ByteArrayInputStream(aByteArray);
final BufferedImage bufferedImage = ImageIO.read(newByteArrayInputStream(aByteArray));
ImageIO.write(bufferedImage, "png", new File("image.png"));
....multiple Errors :image == null! ...... Sure ? Note : I do not search to use a source file
....多个错误:图像 == 空!...... 当然 ?注意:我不搜索使用源文件
采纳答案by prunge
The Image I/O API deals with images, so you need to make an image from your byte array first before you write it out.
Image I/O API 处理图像,因此您需要先从字节数组制作图像,然后再将其写出。
byte[] aByteArray = {0xa,0x2,0xf,(byte)0xff,(byte)0xff,(byte)0xff};
int width = 1;
int height = 2;
DataBuffer buffer = new DataBufferByte(aByteArray, aByteArray.length);
//3 bytes per pixel: red, green, blue
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, 3 * width, 3, new int[] {0, 1, 2}, (Point)null);
ColorModel cm = new ComponentColorModel(ColorModel.getRGBdefault().getColorSpace(), false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
BufferedImage image = new BufferedImage(cm, raster, true, null);
ImageIO.write(image, "png", new File("image.png"));
This assumes the byte array has three bytes per pixel (red, green then blue) and the range of values is 0-255.
这假设字节数组每个像素有三个字节(红色、绿色和蓝色),值的范围是 0-255。