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

问题描述 投票:1回答:1

我有一个字节数组,我的数据存储在每个像素两个字节。我现在想要从这些数据中获得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个字节,我怎么能使这个代码工作?

更新:数据是灰度级的,对不起我之前不知道...所以没有必要得到彩色图像。所以你知道从这个字节数组中获取灰度图像的人是谁?

java image bufferedimage
1个回答
0
投票

在我看来,你必须为每个像素提供3个字节的代码,因此它获得RGB的三种颜色。如果你想这样做只有绿色和蓝色或其他组合,你应该为第三个设置一个默认值...但我不是100%肯定。

© www.soinside.com 2019 - 2024. All rights reserved.