首先,我们必须用您的数据创建一个数据缓冲区
DataBufferByte buffer = new DataBufferByte(data, data.length);
接下来,我们需要声明“bandMasks”,这样光栅才能理解您的格式
int[] bandMasks = {0b11100000, 0b00011100, 0b00000011};
现在,我们可以创建栅格
WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, bandMasks, null);
(仅供参考,宽度被指定两次,因为它是扫描尺寸)
现在我们可以使用缓冲区、光栅和颜色模型创建图像
BufferedImage image = new BufferedImage(new DirectColorModel(8, 0b11100000, 0b00011100, 0b00000011), raster, false, null);
此外,您可以修剪二进制文字中的后续 0,因为这些位默认为 0(0b00000011 与 0b11 相同或(十进制)00029 与 29 相同)您不需要指定所有 32 位一个整数
我验证了之前的代码使用这整个段:
byte[] data = new byte[]{
(byte) 0b00000011/*Blue*/, (byte) 0b11100011/*Purple*/,
(byte) 0b11100011/*Purple*/, (byte) 0b11111111/*White*/};//This is the "image"
int width = 2, height = 2;
DataBufferByte buffer = new DataBufferByte(data, data.length);
int[] bandMasks = {0b11100000, 0b00011100, 0b00000011};
WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, bandMasks, null);
BufferedImage image = new BufferedImage(new DirectColorModel(8, 0b11100000, 0b00011100, 0b00000011), raster, false, null);
JFrame frame = new JFrame("Test");
Canvas c = new Canvas();
frame.add(c);
frame.setSize(1440, 810);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
while (true) {
Graphics g = c.getGraphics();
g.drawImage(image, 0, 0, image.getWidth() * 40, image.getHeight() * 40, null);
}
我希望这会有所帮助!