I have a byte[] array with RGB values. I would like to create BufferedImage without setting the pixels one by one, as the image can be big. I've found the following snippet:
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() ) );
Which does work nice, but there is a small issue ;-) TYPE_3BYTE_BGR is expecting bytes in reverse order.
So the questions are:
Try this code
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With