Android: Convert image object to bitmap does not work
Asked Answered
F

2

6

I am trying to convert image object to bitmap, but it return null.

image = reader.acquireLatestImage();

                        ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                        byte[] bytes = new byte[buffer.capacity()];
                        Bitmap myBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,null);

The image itself is jpeg image, I can save it to the disk fine, the reason I want to convert to bitmap is because I want to do final rotation before saving it to the disk. Digging in the Class BitmapFactory I see this line.

bm = nativeDecodeByteArray(data, offset, length, opts);

This line return null. Further Digging with the debugger

private static native Bitmap nativeDecodeByteArray(byte[] data, int offset,
            int length, Options opts);

This suppose to return Bitmap object but it return null.

Any tricks.. or ideas?

Thanks

Foochow answered 11/6, 2017 at 16:36 Comment(0)
V
9

You haven't copied bytes.You checked capacity but not copied bytes.

ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
Bitmap myBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,null);
Vibrant answered 11/6, 2017 at 17:30 Comment(1)
This does not work for me with a nv21 Image. Is this limited to one of the possible Image formats?Meingolda
D
0

I think you're trying to decode an empty array, you just create it but never copy the image data to it.

You can try:

ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = buffer.array();
Bitmap myBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,null);

As you say it doesn't work, then we need to copy the buffer manually ... try this :)

    byte[] bytes = new byte[buffer.remaining()];
    buffer.get(bytes);
    Bitmap myBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,null);
Donofrio answered 11/6, 2017 at 16:46 Comment(1)
ByteBuffer.Java @throws UnsupportedOperationException If this buffer is not backed by an accessible arrayFoochow

© 2022 - 2024 — McMap. All rights reserved.