如何使用ByteBuffer在本机内存中保存位图图像并将其恢复

问题描述 投票:1回答:2

我从相机直接流,我需要将Bitmap保存到ByteBuffer并恢复它。这是我的代码:

YuvImage yuv = new YuvImage(data.getExtractImageData(), previewFormat, width, height, null);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    yuv.compressToJpeg(new Rect(0, 0, width, height), 50, out);

    byte[] bytes = out.toByteArray();

    Bitmap image = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

    Bitmap imageResult = RotateImage(image, 4 - rotation);
    imageResult = cropBitmap(imageResult, data.getRect());

    int nBytes = imageResult.getByteCount();
    ByteBuffer buffer = ByteBuffer.allocateDirect(nBytes);
    imageResult.copyPixelsToBuffer(buffer);

    return buffer.array();

byte[]转换回Bitmap的代码:

Bitmap bitmap = BitmapFactory.decodeByteArray(images.getImage(), 0, images.getImage().length);

但是之后,bitmap在转换后是空的......

什么是错的?

澄清:我需要将byte[] image保存在Native内存中,这就是我做ByteBuffer.allocateDirect的原因。我需要在特定点裁剪图像,这就是我需要bitmap的原因。

android bytebuffer
2个回答
1
投票

decodeByteArray()对存储在字节数组中的压缩图像(例如JPEG或PNG)进行解码。但是,copyPixelsToBuffer()将“位图”的内容“按原样”复制到字节缓冲区(即未压缩),因此无法通过decodeByteArray()对其进行解码。

如果您不想重新编码位图,可以像使用一样使用copyPixelsToBuffer(),并将第二个代码块更改为使用copyPixelsFromBuffer()而不是decodeByteArray()。

Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(images.getImage()));

你需要保存宽度和高度。还要确保Bitmap.Config是一样的。

基本上,如果你保存它压缩然后你必须加载它压缩,如果你保存未压缩,那么你必须加载它未压缩。


0
投票

您还应该在分配缓冲区时设置字节顺序,因为Java是大端,因此默认情况下缓冲区是大端,android是小端,而底层的cpu架构可能会有所不同,但大多数是endian wrt android:

buffer.order( ByteOrder.nativeOrder() );
© www.soinside.com 2019 - 2024. All rights reserved.