Send image from C ++ to Java using JNI
I am trying to send an image from C ++ to java using JNI. The image is a bitmap created in C ++ where I have cast off pixels with GetDIBits
before char*
. There is no problem when saving an image to a file using C ++, but when sending pixels to Java, the image is all blurry. The JavaDocs say I should use 3BYTE_BGR
for BufferedImage, but I feel like there is something wrong with the compression.
C ++ bitmap
Converting in Java to BufferedImage, width and height are also obtained via jni
This is the result of the image
source to share
Given that bi.bitCount is 32, the use of the format 3BYTE_BGR
for the BufferedImage is incorrect: it assumes one pixel every three bytes, not one pixel every four bytes. Use instead TYPE_INT_BGR
. As we discussed in the comments, your DataBuffer should be DataBufferInt, which you can execute with 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()));
source to share