Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top