JAVA:如何从byte[]创建.PNG图像?

12

我看了一些代码,但不理解...

我使用的是Java 7

请问如何将RGB(红、绿、蓝)字节数组(或类似东西)转换为.PNG文件格式?

例如,从一个可以表示“RGB像素”的数组:

byte[] aByteArray={0xa,0x2,0xf};

重要方面:

我尝试仅从一个byte[]中生成一个.PNG文件,而不是从先前存在的文件中生成。

是否有现有的API可以实现这一点?;)

这是我的第一段代码:

byte[] aByteArray={0xa,0x2,0xf}; 
ByteArrayInputStream bais = new ByteArrayInputStream(aByteArray); 
File outputfile = new File("image.png"); 
ImageIO.write(bais, "png", outputfile); 

....错误:没有找到合适的方法

这是从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")); 

...多个错误:图像为null!......确定吗?注:我不打算使用源文件


请您能否把您不理解的代码贴出来,我们会帮助您。 - wattostudios
1个回答

16

图像 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"));

假设字节数组每个像素有三个字节(红色、绿色和蓝色),值的范围为0-255。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接