Upload a PNG image in Java as a BufferedImage via JNI C code

I have the following problem. I have a C code that takes a PNG image as input and stores it in memory. I would like this raw data to be translated into BufferedImage in Java using JNI. Does anyone know of any way to do this or have done it before?

+2
source share
3 answers

I assume that you know the basics of function calls using JNI. It's not that difficult, although it can be a pain in the ass.

If you want to do this quickly, just write the PNG to the temp file, transfer the file name via JNI and upload it using ImageIO.

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

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

+4
source

If you have never used JNI before, I recommend that you take a look at the JNI Programmers Guide and Specification .

In general, you need to do the following:

  • Create a Java method with the native keyword without implementation.
  • use the javah command in a class with its own method to create a header file (.h). javah comes with a JDK installation.
  • implement native Java function in C / C ++.
    • find the java.awt.image.BufferedImage class.
    • Find the constructor you want to use.
    • create a BufferedImage object with the specified constructor.
    • find the setPixel method.
    • run this method to set each pixel value in your image. you will need to run its height x width times.
    • return an object.
  • compile your own file into a shared library.
  • load your shared library into your java class.
  • run your java class with a link to your shared library.

There are other ways to copy the raw data of your image, but as I explained, should be enough.

+1
source

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

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

0
source

All Articles