Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a BMP file from raw byte[] in Java

I have a C++ application which communicates with a camera and fetches raw image-data. I then have a Byte[] in C++, which i want to send to Java with JNI.

However, i need to convert the raw Byte[] to an real file format(.bmp was my first choice). I can easily do this if i write it from C++ to an file on the hard-drive, using BITMAPFILEINFO and BITMAPHEADERINFO, but i do not know how one would go about sending the entire-format to Java.

Then i thought about sending only the raw byte[] data using JNI and then converting it to .bmp, but i can't seem to find any good library for doing this in Java.

What would be my best choice? Converting the image in C++ and then sending it using JNI or send the RAW data to Java and then convert it to .bmp? How would i easiest achieve this?

like image 967
Silfverstrom Avatar asked Jul 28 '09 12:07

Silfverstrom


People also ask

How do you create a bitmap image in Java?

To create a bitmap from a resource, you use the BitmapFactory method decodeResource(): Bitmap bitmap = BitmapFactory. decodeResource(getResources(), R. drawable.

What is raw bytes in Java?

The data are written as a stream of bytes. There are no gaps or markers that say where one value ends and another begins. The example program did this: dataOut.


2 Answers

It's just two lines in Java 1.5:

BufferedImage image = ImageIO.read( new ByteArrayInputStream( byteArray ) );
ImageIO.write(image, "BMP", new File("filename.bmp"));

Java (on Windows) knows how to export jpg, png and bmp as far as i know.

like image 108
Stroboskop Avatar answered Oct 19 '22 01:10

Stroboskop


There's no need to do any of that. Turn the byte array into an InputStream and feed that to ImageIO.read();

public Image getImageFromByteArray(byte[] byteArray){
    InputStream is = new ByteArrayInputStream(byteArray);
    return ImageIO.read(is);
} 

This creates an Image object from your byte array, which is then very trivial indeed to display inside a gui component. Should you want to save it, you can use the ImageIO class for that as well.

public void saveImage(Image img, String fileFormat, File f){
    ImageIO.write(img, fileFormat, f);
}
like image 43
Markus Koivisto Avatar answered Oct 19 '22 01:10

Markus Koivisto