如何从字节数组(2字节/像素)获取PNG?

时间:2019-03-01 13:57:35

标签: java image bufferedimage

我有一个字节数组,我的数据每像素存储两个字节。我现在想从此数据中获取PNG。我找到了一个不错的代码here

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

作者在这里使用每个像素3个字节。所以我的问题是:如果我的字节数组每个像素有2个字节,如何使此代码正常工作?

更新: 数据是灰度的,对不起,我以前没看过……所以不需要获取彩色图像。那么您知道谁能从此字节数组中获得灰度图像吗?

1 个答案:

答案 0 :(得分:0)

我认为您必须将此代码提供给每个像素3个字节,因此它获得了RGB的三种颜色。如果您只想使用绿色和蓝色或其他组合来做到这一点,则应该为第三个设置默认值...但是我不确定100%。