简体   繁体   English

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

[英]Android: Convert image object to bitmap does not work

I am trying to convert image object to bitmap, but it return null. 我试图将图像对象转换为位图,但它返回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. 图像本身是jpeg图像,我可以将它保存到磁盘上,我想转换为位图的原因是因为我想在将其保存到磁盘之前进行最终旋转。 Digging in the Class BitmapFactory I see this line. 在BitmapFactory类中挖掘我看到这一行。

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

This line return null. 该行返回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. 这假设返回Bitmap对象但它返回null。

Any tricks.. or ideas? 任何技巧..或想法?

Thanks 谢谢

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);

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM