I am using JNA. and i am getting byte array of raw data from my c++ method. Now i am stuck how to get buffered image in java using this raw data byte array. I had tried few things to get it as tiff image but i dint get success. this are the code i tried so far. here my byte array contains data for 16 bit gray scale image. i get this data from x-sensor device. and now i need to get image from this byte array.
FIRST TRY
byte[] byteArray = myVar1.getByteArray(0, 3318000);//array of raw data
ImageInputStream stream1=ImageIO.createImageInputStream(newByteArrayInputStream(byteArray));
ByteArraySeekableStream stream=new ByteArraySeekableStream(byteArray,0,3318000);
BufferedImage bi = ImageIO.read(stream);
SECOND TRY
SeekableStream stream = new ByteArraySeekableStream(byteArray);
String[] names = ImageCodec.getDecoderNames(stream);
ImageDecoder dec = ImageCodec.createImageDecoder(names[0], stream, null);
//at this line get the error ArrayIndexOutOfBoundsException: 0
RenderedImage im = dec.decodeAsRenderedImage();
I think i am missing here. As my array is containing raw data ,it does not containthen header for tiff image. m i right? if yes then how to provide this header in byte array. and eventually how to get image from this byte array?
to test that i am getting proper byte array from my native method i stored this byte array as .raw file and after opening this raw file in ImageJ software it sows me correct image so my raw data is correct. The only thing i need is that how to convert my raw byte array in image byte array?
Whether or not the byte array contains literally just pixel data or a structured image file such as TIFF etc really depends on where you got it from. It's impossible to answer that from the information provided.
However, if it does contain a structured image file, then you can generally:
If you just have literally raw pixel data, then you have a couple of main options:
I think the above is easiest if you know what you're doing with the bits and bytes. However, in principle, you should be able to do the following:
Here is what I am using to convert raw pixel data to a
BufferedImage
. My pixels are signed 16-bit:I'm then using JAI to encode the resulting image. Tell me if you need the code as well.
EDIT: I have greatly improved the speed thanks to @Brent Nash answer on a similar question.
EDIT: For the sake of completeness, here is the code for unsigned 8 bits: