[英]Load a PNG image into Java as BufferedImage through JNI C code
I have the following problem. 我有以下问题。 I have C code that acquires a PNG image as basically raw data and keeps it in memory. 我有C代码,基本上将PNG图像获取为原始数据并将其保存在内存中。 I would like this raw data to be translated to a BufferedImage in Java, through the use of JNI. 我希望通过使用JNI将原始数据转换为Java中的BufferedImage。 Does anyone know any way of doing this or has done this before? 有谁知道这样做或以前做过的任何方式?
I'll assume you know the basics of how to call functions with JNI. 我假设您了解如何使用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. 如果要快速完成,只需将PNG写入临时文件,通过JNI传递文件名,然后使用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. 如果您想变得更复杂,并且避免需要文件路径,则可以在ByteArrayInputStream上使用ImageIO.read(InputStream) ,该数组包装通过JNI传递的字节数组。 You can call NewByteArray() from C and then use SetByteArrayRegion to set the data. 您可以从C调用NewByteArray() ,然后使用SetByteArrayRegion设置数据。
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. 最后,您可能考虑使用HTTP传输数据,Apache 可以使用一组组件 ,其中包括一个小型Web服务器,您可以将C代码发布到Java。
if you've never used JNI before, I'd recommend you to take a look at the JNI Programmer's Guide and Specification . 如果您以前从未使用过JNI,建议您阅读JNI程序员指南和规范 。
in summary, what you have to do is: 总之,您需要做的是:
native
keyword, with no implementation. 使用native
关键字创建Java方法,而无需实现。 javah
on the class with the native method to generate a header file (.h). 在带有本机方法的类上使用命令javah
生成头文件(.h)。 javah
comes with a JDK installation. javah
随附JDK安装。 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. 由于Java库支持PNG,因此我将添加一种机制,将所有字节从C复制到Java并按照Chad Okere的建议使用ImageIO类。
Also, consider using JNA to make life easier ( example using JNA to draw a Windows cursor ). 另外,考虑使用JNA来简化生活( 例如,使用JNA绘制Windows光标 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.