Load a PNG image into Java as BufferedImage through JNI C code

我的未来我决定 提交于 2020-01-02 11:14:06

问题


I have the following problem. I have C code that acquires a PNG image as basically raw data and keeps it in memory. I would like this raw data to be translated to a BufferedImage in Java, through the use of JNI. Does anyone know any way of doing this or has done this before?


回答1:


I'll assume you know the basics of how to call functions with JNI. It's not that complicated, although it can be a pain in the ass.

If you want to get it done quickly, just write the PNG to a temp file, pass the file name up through JNI and load it using ImageIO.

If you want to get more sophisticated, and avoid needing a file path, you can use ImageIO.read(InputStream) on a ByteArrayInputStream that wraps a byte array you pass in through JNI. You can call NewByteArray() from C and then use SetByteArrayRegion to set the data.

Finally, you might consider using HTTP to transfer the data, Apache has a set of components you can use that include a little web server, you can POST from your C code to Java.




回答2:


if you've never used JNI before, I'd recommend you to take a look at the JNI Programmer's Guide and Specification.

in summary, what you have to do is:

  1. create a Java method with the native keyword, with no implementation.
  2. use the command javah on the class with the native method to generate a header file (.h). javah comes with a JDK installation.
  3. implement your native Java function in C/C++.
    1. search the class java.awt.image.BufferedImage.
    2. search the constructor you want to use.
    3. create a BufferedImage object with the specified constructor.
    4. search the setPixel method.
    5. run that method to set each pixel value in your image. you'll need to run it height x width times.
    6. return the object.
  4. compile your native file into a shared library.
  5. load your shared library inside your Java class.
  6. run your Java class indicating, linking your shared library.

there are other ways of copying the raw data of your image, but this way I explained should be enough.




回答3:


Since the Java library supports PNG, I would add a mechanism that copied all the bytes from C to Java and use the ImageIO class as Chad Okere suggests.

Also, consider using JNA to make life easier (example using JNA to draw a Windows cursor).



来源:https://stackoverflow.com/questions/842386/load-a-png-image-into-java-as-bufferedimage-through-jni-c-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!