问题
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:
- create a Java method with the
native
keyword, with no implementation. - use the command
javah
on the class with the native method to generate a header file (.h).javah
comes with a JDK installation. - implement your native Java function in C/C++.
- search the class java.awt.image.BufferedImage.
- search the constructor you want to use.
- create a BufferedImage object with the specified constructor.
- search the setPixel method.
- run that method to set each pixel value in your image. you'll need to run it height x width times.
- return the object.
- compile your native file into a shared library.
- load your shared library inside your Java class.
- 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