简体   繁体   English

如何在Java中使用raw byte []创建BMP文件

[英]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. 我有一个C ++应用程序,它与相机通信并获取原始图像数据。 I then have a Byte[] in C++, which i want to send to Java with JNI. 然后我在C ++中有一个Byte [],我想用JNI发送给Java。

However, i need to convert the raw Byte[] to an real file format(.bmp was my first choice). 但是,我需要将原始Byte []转换为真实的文件格式(.bmp是我的第一选择)。 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. 如果我使用BITMAPFILEINFO和BITMAPHEADERINFO将它从C ++写入硬盘驱动器上的文件,我可以很容易地做到这一点,但我不知道如何将整个格式发送到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. 然后我考虑使用JNI仅发送原始byte []数据,然后将其转换为.bmp,但我似乎无法在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? 用C ++转换图像然后使用JNI发送它或将RAW数据发送到Java然后将其转换为.bmp? How would i easiest achieve this? 我最容易实现这一目标?

It's just two lines in Java 1.5: 它只是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. 据我所知,Java(在Windows上)知道如何导出jpg,png和bmp。

There's no need to do any of that. 没有必要做任何这些。 Turn the byte array into an InputStream and feed that to ImageIO.read(); 将字节数组转换为InputStream并将其提供给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. 这将从您的字节数组创建一个Image对象,这在gui组件内显示非常微不足道。 Should you want to save it, you can use the ImageIO class for that as well. 如果您想保存它,您也可以使用ImageIO类。

public void saveImage(Image img, String fileFormat, File f){
    ImageIO.write(img, fileFormat, f);
}

If you know how to write as .bmp to a file, then you can use (almost) the same code for writing into a memory buffer instead. 如果您知道如何将.bmp写入文件,那么您可以使用(几乎)相同的代码来写入内存缓冲区。 That memory buffer you can ship over to Java, and have it decode the format like Stroboskop or Markus Koivisto mentioned. 你可以将这个内存缓冲区运送到Java,并让它解码像Stroboskop或Markus Koivisto这样的格式。 If you edited your question to include the way you write the data to a .bmp file, I could suggest how to convert that into an in-memory operation. 如果您编辑了问题以包括将数据写入.bmp文件的方式,我可以建议如何将其转换为内存中操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM