views:

1823

answers:

3

Hi,

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?

A: 

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.

cd1
Thanks for the reply, I ended up doing it a different way.
ldog
+3  A: 

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.

Chad Okere
Hey Chad,Thanks for the comment this is actually exactly what I ended up doing, albeit I read how to do it after I actually did it :)
ldog
A: 

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

McDowell
Hey,Fortunately I don't use Windows for anything so I can't use JNA. Thanks for the heads up, if I ever switch back to windows I will find that useful.
ldog