How to convert ByteBuffer into image in Android

zelf picture zelf · Jul 28, 2016 · Viewed 14.8k times · Source

I am receiving jpg image through socket and it is sent as ByteBuffer what I am doing is:

        ByteBuffer receivedData ;
        // Image bytes
        byte[] imageBytes = new byte[0];
        // fill in received data buffer with data
        receivedData=  DecodeData.mReceivingBuffer;
        // Convert ByteByffer into bytes
        imageBytes = receivedData.array();
        //////////////
        // Show image
        //////////////
        final Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes,0,imageBytes.length);
        showImage(bitmap1);

But what is happening that it fails to decode the imageBytes and bitmap is null.

Also I got imagebytes as: imageBytes: {-1, -40, -1, -32, 0, 16, 74, 70, 73, 70, 0, 1, 1, 1, 0, 96, 0, 0, 0, 0, -1, -37, 0, 40, 28, 30, 35, +10,478 more}

What would be the problem? is it decoding problem? or conversion from ByteBuffer to Byte array?

Thanks in advance for help.

Answer

Asaf Pinhassi picture Asaf Pinhassi · Sep 28, 2016

This one worked for me (for ARGB_8888 pixel buffer):

private Bitmap getBitmap(Buffer buffer, int width, int height) {
    buffer.rewind();
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(buffer);
    return bitmap;
}