我从相机直接流,我需要将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
的原因。
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
是一样的。
基本上,如果你保存它压缩然后你必须加载它压缩,如果你保存未压缩,那么你必须加载它未压缩。
您还应该在分配缓冲区时设置字节顺序,因为Java是大端,因此默认情况下缓冲区是大端,android是小端,而底层的cpu架构可能会有所不同,但大多数是endian wrt android:
buffer.order( ByteOrder.nativeOrder() );