1

I want to write a utility which converts org.bytedeco.javacpp.lept.PIX to byte[] and BufferedImage. I have tried the following:

1) using Java2DFrameUtils but it inverts my image colors ( 1-> 0 and 0-> 1) with the code:

LeptonicaFrameConverter c = new LeptonicaFrameConverter();
 Frame f = c.convert(src);
 BufferedImage img = Java2DFrameUtils.toBufferedImage(f);

2) this approach does not use the org.bytedeco.javacpp package, so it does not help me.

3) When I try to use PointerPointer and SizeTPointer of this package, I get error saying

"Error in pixWriteMem: &data not defined".

Here is my code:

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

Any help would be appreciated. TIA.

vamsiampolu
  • 6,328
  • 19
  • 82
  • 183

1 Answers1

1

I guess that I'm a bit late here. but if somebody reaches this post in the future, here is how I dealt with this issue.

The issue is that neither buffer nor psize are initialised. So I use 0 as the size of the buffer, call pixWriteMem that returns the buffer size in the psize pointer. Then call pixWriteMem again with a buffer of the expected size.

Caution: If you work with very large images check the potential issues with the toInt() calls!

If something goes wrong and gotSize is always different of size, this can lead to an endless loop with a StackOverFlow exception.

The sample code is in 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()
}
Xvolks
  • 2,065
  • 1
  • 21
  • 32