简体   繁体   中英

Send image from C++ to Java using JNI

I'm trying to send an image from C++ to java using JNI. The image is a bitmap created in C++ where I cast the pixels using GetDIBits to a char* . When saving the image to a file using C++ there are no problems but when sending the pixels to Java the image is all blurry. The JavaDocs say I have to use 3BYTE_BGR for BufferedImage but I feel there is something wrong in the compression

The C++ bitmap

Converting in Java to BufferedImage, the width and height are also received through jni

This is the result of the image

Given that bi.bitCount is 32, using 3BYTE_BGR format for BufferedImage is incorrect: it's assuming one pixel every three bytes, rather than one pixel every four bytes. Instead, use TYPE_INT_BGR . As we discussed in the comments, your DataBuffer will need to be a DataBufferInt, which you can accomplish by using ByteBuffer and IntBuffer, as in the following snippet:

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
IntBuffer intBuffer = ByteBuffer.wrap(img).asIntBuffer();
int[] imgInts = new int[img.length * Byte.SIZE / Integer.SIZE];
intBuffer.get(imgInts);
image.setData(Raster.createRaster(image.getSampleModel(), new DataBufferInt(imgInts, imgInts.length), new Point()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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