How to convert byte array to Image in Java SE

What is the correct way to convert a raw byte array into Image in Java SE. the array consists of bytes, where each three bytes represent one pixel with each byte for the corresponding RGB component.

Can anyone suggest a sample code?

Thanks Mike

+5
java image graphics
source share
4 answers

Assuming you know the height and width of the image.

BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for(int r=0; r<height; r++) for(int c=0; c<width; c++) { int index=r*width+c; int red=colors[index] & 0xFF; int green=colors[index+1] & 0xFF; int blue=colors[index+2] & 0xFF; int rgb = (red << 16) | (green << 8) | blue; img.setRGB(c, r, rgb); } 

Rough. This assumes that the pixel data is encoded as a set of strings; and that the color length is 3 * width * height (which should be valid).

+6
source share

You can do this using the Raster class. This is better because it does not require iterating and copying byte arrays.

  byte[] raw = new byte[width*height*3]; // raw bytes of our image DataBuffer buffer = new DataBufferByte(raw, raw.length); //The most difficult part of awt api for me to learn SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, width, height, 3, width*3, new int[]{2,1,0}); Raster raster = Raster.createRaster(sampleModel, buffer, null); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); image.setData(raster); 
+8
source share

folkyatina is suitable if your RGB values ​​are in the order of B, G, R, but if they are in the order of R, G, B, I found the following code to work:

  DataBuffer rgbData = new DataBufferByte(rgbs, rgbs.length); WritableRaster raster = Raster.createInterleavedRaster( rgbData, width, height, width * 3, // scanlineStride 3, // pixelStride new int[]{0, 1, 2}, // bandOffsets null); ColorModel colorModel = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[]{8, 8, 8}, // bits false, // hasAlpha false, // isPreMultiplied ComponentColorModel.OPAQUE, DataBuffer.TYPE_BYTE); return new BufferedImage(colorModel, raster, false, null); 
+2
source share

There is a setRGB option that accepts an int array of RGBA values:

 BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); int[] raw = new int[data.length * 4 / 3]; for (int i = 0; i < data.length / 3; i++) { raw[i] = 0xFF000000 | ((data[3 * i + 0] & 0xFF) << 16) | ((data[3 * i + 1] & 0xFF) << 8) | ((data[3 * i + 2] & 0xFF)); } img.setRGB(0, 0, width, height, raw, 0, width); 

Performance characteristics are similar to CoderTao solutions.

+1
source share

All Articles