此代码如下:
public static Bitmap getScreenShot(ImageReader imageReader) {
Bitmap bitmap = null;
Image image = imageReader.acquireLatestImage();
if (image != null) {
int width = image.getWidth();
int height = image.getHeight();
final Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * width;
if(imageReader.getSurface() != null && imageReader.getSurface().isValid()){
bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_4444);
bitmap.copyPixelsFromBuffer(buffer);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
}
image.close();
}
return bitmap;
}
现在,我想使用BitmapFactory.decodeByteArray()
重用位图内存,但在使用ByteBuffer
将byte[]
转换为byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes)
后,结果bytes
没用。那么如何实现上述目标?
错误代码如下:
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static byte[] getScreenShot(ImageReader imageReader) {
Bitmap bitmap = null;
byte[] bytes = null;
Image image = imageReader.acquireLatestImage();
if (image != null) {
int width = image.getWidth();
int height = image.getHeight();
final Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[0].getBuffer();
if(buffer.hasArray()){
bytes = buffer.array();
}else {
bytes = new byte[buffer.remaining()];
((ByteBuffer)(buffer.duplicate().clear())).get(bytes, 0, bytes.length);
}
image.close();
}
return bytes;
}