为了账号安全,请及时绑定邮箱和手机立即绑定

来自 RGB byte[] 数组的 BufferedImage

来自 RGB byte[] 数组的 BufferedImage

子衿沉夜 2024-01-05 16:54:05
我有一个包含 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期望字节以相反的顺序排列。所以问题是:是否可以以某种方式加载我的数组,而无需实际创建具有预期顺序的新字节数组?如果不可能,是否有比 for 循环更好的方法将数据从 RGB 格式复制到 BGR?
查看完整描述

2 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

试试这个代码


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

        }


查看完整回答
反对 回复 2024-01-05
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

前面的答案有效,但可以简化以更具可读性:


ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);


ColorModel model = new ComponentColorModel(

    colorSpace, 

    false,

    true, 

    Transparency.OPAQUE, 

    DataBuffer.TYPE_BYTE

);


WritableRaster raster = Raster.createInterleavedRaster(

    DataBuffer.TYPE_BYTE, 

    width, 

    height, 

    3, 

    null

);


BufferedImage image = new BufferedImage(model, raster, true, null);


查看完整回答
反对 回复 2024-01-05
  • 2 回答
  • 0 关注
  • 62 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信