如何修复'AcquireLatestImage()'获取null

时间:2019-11-11 23:32:23

标签: c# xamarin android-mediaprojection

我正在使用Mediaprojection API。但是当我调用AcquirelatestImage()时,我返回null。所以我用Do〜While当It调用值时,它调用1000〜1800时间来获取值。我如何一次获得价值?

  private void setUpVirtualDisplay()
    {
        imageReader = ImageReader.NewInstance(displayWidth, 
  displayHeight, (ImageFormatType)Android.Graphics.Format.Rgba8888, 2);
        virtualDisplay = 
SharedVariable.mediaProjection.CreateVirtualDisplay("ScreenCapture",
               displayWidth, displayHeight, screenDensity,
                (DisplayFlags)VirtualDisplayFlags.AutoMirror, 
 imageReader.Surface, null, null);

        ScreenCapture = screenshot();

        bool value = MailingSystem(ScreenCapture);
    }
  private byte[] screenshot()
    {
        Image image = null;
        int cnt = 0;
        do
        {
            image = imageReader.AcquireLatestImage();
            cnt += 1;
        } while (image == null);
        if (image != null)
        {
            Image.Plane[] planes = image.GetPlanes();
            ByteBuffer buffer = planes[0].Buffer;
            int pixelStride = planes[0].PixelStride;
            int rowStride = planes[0].RowStride;
            int rowPadding = rowStride - pixelStride * displayWidth;

            // バッファからBitmapを生成
            Bitmap bitmap = Bitmap.CreateBitmap(
                    displayWidth + rowPadding / pixelStride,displayHeight,
                    Bitmap.Config.Argb8888);
            bitmap.CopyPixelsFromBuffer(buffer);
            if (virtualDisplay != null)
            {
                virtualDisplay.Release();
            }
            if (imageReader != null)
            {
                imageReader.SetOnImageAvailableListener(null, null);
            }

            using (var stream = new MemoryStream())
            {
                bitmap.Compress(Bitmap.CompressFormat.Png, 90, stream);
                return stream.ToArray();
            }
        }
        return null;

    }

那我该如何解决这个问题?

enter image description here

0 个答案:

没有答案