2017-07-03 45 views
0

我有一個字節數組,其中每個字節描述一個像素(256色)。這是我使用的位掩碼: 0xRRRGGGBB 所以R和G分量有3位,B分量有2位。 假設我知道圖像的寬度和高度,如何從該數組構造BufferedImage?3/3/2 RGB樣本的字節數組到Java中的BufferedImage

+0

爲什麼你需要三位紅色和綠色?通常的位掩碼是「RRGGBBAA」(或「AARRGGBB」),其中「A」代表阿爾法。 – Tom

+0

我不需要alpha組件來達到我的目的。我構建了顏色模型:'DirectColorModel model = new DirectColorModel(8,0b00000000000000000000000000000001000000000000000000000000000000000000011100,0B00000000000000000000000000000011)'和buffer:'DataBufferByte buffer = new DataBufferByte(data,data.length)''但是我不知道如何構造光柵 – ddms

+0

假如我有RRGGBBAA掩碼,我將如何構建BufferedImage? – ddms

回答

2

首先,我們必須創建與您的數據
DataBufferByte buffer = new DataBufferByte(data, data.length);

下一個數據緩衝區,我們需要聲明「bandMasks」這樣的光柵可以瞭解您的格式現在
int[] bandMasks = {0b11100000, 0b00011100, 0b00000011};

,我們可以創建光柵
WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, bandMasks, null); (FYI,寬度指定兩次,因爲它是掃描)

現在,我們可以創建一個緩衝區,光柵和顏色模型圖像
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); 
    } 

我希望這有助於!

+0

謝謝,這將是有益的! – ddms