Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get buffered image from byte array of raw data

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?

like image 845
Jony Avatar asked Dec 15 '22 23:12

Jony


1 Answers

Here is what I am using to convert raw pixel data to a BufferedImage. My pixels are signed 16-bit:

public static BufferedImage short2Buffered(short[] pixels, int width, int height) throws IllegalArgumentException {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_USHORT_GRAY);
    short[] imgData = ((DataBufferShort)image.getRaster().getDataBuffer()).getData();
    System.arraycopy(pixels, 0, imgData, 0, pixels.length);     
    return image;
}

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:

public static BufferedImage byte2Buffered(byte[] pixels, int width, int height) throws IllegalArgumentException {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
    byte[] imgData = ((DataBufferByte)image.getRaster().getDataBuffer()).getData();
    System.arraycopy(pixels, 0, imgData, 0, pixels.length);     
    return image;
}
like image 132
Matthieu Avatar answered Dec 30 '22 18:12

Matthieu