Android: 将图像对象转换为位图不起作用

Android: Convert image object to bitmap does not work

我正在尝试将图像对象转换为位图,但它 return 为空。

image = reader.acquireLatestImage();

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

图像本身是jpeg图像,我可以把它保存到磁盘上,我想转换成位图的原因是我想在保存到磁盘之前做最后的旋转。 在 Class BitmapFactory 中挖掘我看到了这一行。

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

此行return 为空。 使用调试器进一步挖掘

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

这假设为 return 位图对象,但它 return 为空。

有什么技巧……或想法吗?

谢谢

我认为您正在尝试解码一个空数组,您只是创建它但从未将图像数据复制到它。

你可以试试:

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

正如你所说的那样不起作用,那么我们需要手动复制缓冲区...试试这个:)

    byte[] bytes = new byte[buffer.remaining()];
    buffer.get(bytes);
    Bitmap myBitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length,null);

您没有复制 bytes.You 检查容量但没有复制字节。

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