Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedImage from RGB byte[] array

Tags:

java

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:

  1. Is it possible to load my array somehow without actually creating a new byte array with expected ordering?
  2. If its not possible, is there any better way than for loop to copy data from RGB format to BGR?
like image 963
marxin Avatar asked Jun 19 '26 22:06

marxin


1 Answers

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);
        }
like image 88
Diego Marin Santos Avatar answered Jun 23 '26 01:06

Diego Marin Santos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!