Search code examples
javaimage-processingawtbufferedimageraster

BufferedImage from 4-bit data buffer


Hello I have a problem with converting my 4-bit data buffer to WritableRaster. Image resolution: 1024x768 (786432)

Here is description what I'm doing.

1) Create 4-bit BufferedImage

bit4Image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY, MY_BIT_4_COLOR_MODEL);
Graphics graphics = bit4Image.getGraphics();
graphics.drawImage(originalImage, 0, 0, null);
graphics.dispose();
//4-bit BufferedImage created. 4-bit BufferedImage is properly made cause it can be saved to hdd and looks good

2) Get byte array from DataBuffer from 4-bit

byte[] pixelData = ((DataBufferByte)  bit4Image.getRaster().getDataBuffer()).getData();
// pixelData length is 393216

3) Now I want to create BufferedImage from this byte array pixelData

BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY, MY_BIT_4_COLOR_MODEL);
DataBufferByte buffer = new DataBufferByte(pixelData, pixelData.length);
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, width, 1, new int[]{0}, new Point(0, 0));
dest.setData(raster);

Problem is when I call Raster.createInterleavedRaster. Exception: java.awt.image.RasterFormatException: Data array too small (should be > 786431 )

I also tried something like this

BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY, MY_BIT_4_COLOR_MODEL);
dest.getRaster().setDataElements(0, 0, width, height, pixelData);

But this one gives me similar failure:
java.lang.ArrayIndexOutOfBoundsException: 393216

Could someone give me a hint or show the proper way of setting this 4-bit pixelData to WritableRaster?


Solution

  • Resolved. I just had to create WritableRaster with giving it SampleModel:
    SampleModel sm = MY_BIT_4_COLOR_MODEL.createCompatibleSampleModel(width, height); WritableRaster wr = Raster.createWritableRaster(sm, buffer, new Point(0,0));