简体   繁体   English

来自 RGB byte[] 数组的 BufferedImage

[英]BufferedImage from RGB byte[] array

I have a byte[] array with RGB values.我有一个带有 RGB 值的 byte[] 数组。 I would like to create BufferedImage without setting the pixels one by one, as the image can be big.我想创建 BufferedImage 而不一一设置像素,因为图像可能很大。 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.这确实很好用,但有一个小问题;-) TYPE_3BYTE_BGR期望字节顺序相反。

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?如果不可能,有没有比for循环更好的方法将数据从RGB格式复制到BGR?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM