我想编写一个实用程序,将 org.bytedeco.javacpp.lept.PIX
转换为 byte[]
和 BufferedImage
。我尝试过以下方法:
1) 使用 Java2DFrameUtils 但它使用以下代码反转我的图像颜色(1-> 0 和 0-> 1):
LeptonicaFrameConverter c = new LeptonicaFrameConverter();
Frame f = c.convert(src);
BufferedImage img = Java2DFrameUtils.toBufferedImage(f);
2) this方法不使用 org.bytedeco.javacpp 包,所以它对我没有帮助。
3) 当我尝试使用此包的 PointerPointer
和 SizeTPointer
时,出现错误消息
"Error in pixWriteMem: &data not defined".
这是我的代码:
PointerPointer pp = new PointerPointer();
SizeTPointer psize = new SizeTPointer();
lept.pixWriteMem(pp, psize, src, lept.IFF_TIFF);
byte[] by = pp.asByteBuffer().array();
BufferedImage img = ImageIO.read(new ByteArrayInputStream(by));
如有任何帮助,我们将不胜感激。 TIA。
最佳答案
我想我来晚了一点。但如果将来有人看到这篇文章,我将按照以下方式处理此问题。
问题是 buffer
都没有也不psize
已初始化。
所以我用0
作为缓冲区的大小,调用 pixWriteMem
返回 psize
中的缓冲区大小指针。然后调用pixWriteMem
再次使用预期大小的缓冲区。
警告:如果您使用非常大的图像,请检查 toInt()
的潜在问题。来电!
如果出现问题并且 gotSize
总是与 size
不同,这可能会导致无限循环并出现 StackOverFlow 异常。
示例代码采用 Kotlin 语言。
@Throws(IOException::class)
fun convertPixToImage(pix: PIX?, size: Int = 0): ByteArray {
val buffer = ByteBuffer.allocate(size)
val psize = SizeTPointer(size.toLong())
val format = IFF_PNG
if (0 != lept.pixWriteMem(buffer, psize, pix, format)) {
throw IllegalArgumentException("Cannot convert image")
}
val gotSize = psize.get().toInt()
if (gotSize != size) {
return convertPixToImage(pix, gotSize)
}
return buffer.array()
}
关于java - 想要将 org.bytedeco.javacpp.lept.PIX 转换为 byte[] 和缓冲图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54548155/