如何从表面返回位图的byte []

时间:2018-06-13 10:36:57

标签: android android-bitmap bytebuffer surface

此代码如下:

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()重用位图内存,但在使用ByteBufferbyte[]转换为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;
}

0 个答案:

没有答案