使用 JNI 将图像从C++发送到 Java

Send image from C++ to Java using JNI

本文关键字:Java C++ JNI 图像 使用      更新时间:2023-10-16

我正在尝试使用JNI将图像从C++发送到java。该图像是在C++中创建的位图,我在其中使用GetDIBits将像素投射到char*。使用C++将图像保存到文件时没有问题,但是将像素发送到Java时,图像都是模糊的。JavaDocs说我必须为BufferedImage使用3BYTE_BGR,但我觉得压缩有问题

C++位图

在Java中转换为BufferedImage,宽度和高度也通过jni接收

这是图像的结果

鉴于 bi.bitCount 是 32,使用 BufferedImage 3BYTE_BGR格式是不正确的:它假设每三个字节一个像素,而不是每四个字节一个像素。 请改用 TYPE_INT_BGR 。 正如我们在注释中所讨论的,您的 DataBuffer 需要是一个 DataBufferInt,您可以使用 ByteBuffer 和 IntBuffer 来完成,如以下代码片段所示:

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