MicroHat11
MicroHat11

Reputation: 227

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

Upvotes: 3

Views: 1240

Answers (1)

Derek T. Jones
Derek T. Jones

Reputation: 1812

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()));

Upvotes: 1

Related Questions