BufferedImage来自RGB byte[]数组



我有一个带有RGB值的byte[]数组。我想在不逐个设置像素的情况下创建BufferedImage,因为图像可能很大。我发现了以下片段:

byte[] frame = ...;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
img.setData(Raster.createRaster(img.getSampleModel(), new DataBufferByte(frame, frame.length), new Point() ) );

这确实很好,但有一个小问题;-(TYPE_3BYTE_BGR需要按相反顺序排列的字节。

所以问题是:

  1. 是否可以以某种方式加载我的数组,而不实际创建具有预期顺序的新字节数组
  2. 如果不可能,有没有比循环将数据从RGB格式复制到BGR更好的方法

试试这个代码

BufferedImage img = create3ByteRGBImage(int width, int height, new int[] {8, 8, 8},
new int[] {0, 1, 2});    
private BufferedImage create3ByteRGBImage(width, height, int[] nBits, int[] bOffs) {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
ColorModel colorModel =
new ComponentColorModel(cs, nBits,
false, false,
Transparency.OPAQUE,
DataBuffer.TYPE_BYTE);
WritableRaster raster =
Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,
width, height,
width*3, 3,
bOffs, null);
return new BufferedImage(colorModel, raster, false, null);
}

最新更新