Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array of bytes into Image in Java SE

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

Can anybody suggest a code sample?

Thanks, Mike

like image 435
Ma99uS Avatar asked Jul 17 '09 13:07

Ma99uS


People also ask

What is byte array image?

Images are binary data - this is easily represented as byte arrays. The image in the sample is stored in the database as a BLOB - not a string or location, that is, it is binary data.

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.

Can we convert byte array to file in Java?

In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.


1 Answers

You can do it using Raster class. It's better because it does not require iterating and copying of 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);
like image 167
Aleksei Potapkin Avatar answered Sep 22 '22 20:09

Aleksei Potapkin