Image Reader Works on Virtual Device, Not on Real Device

89 views Asked by At

Image Reader Not Working on Real Device

In Media Projection, when trying to capture the screen with the createVirtualDisplay function, ImageReader is running in Virtual Device and it always captures different images, but after capturing several images in Real Device it always saves the same images.

I tried a lot on the code, but I couldn't find a solution in ImageReader part.

The createVirtualDisplay side is as follows;

private void createVirtualDisplay() {
        // get width and height
        mWidth = Resources.getSystem().getDisplayMetrics().widthPixels;
        mHeight = Resources.getSystem().getDisplayMetrics().heightPixels;

        // start capture reader
        mImageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 10);
        mVirtualDisplay = mMediaProjection.createVirtualDisplay(
                SCREENCAP_NAME,
                mWidth,
                mHeight,
                mDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mImageReader.getSurface(),
                null,
                mHandler);
        mImageReader.setOnImageAvailableListener(new ImageAvailableListener(), mHandler);
    }

ImageAvailableListener side is as follows;

private class ImageAvailableListener implements ImageReader.OnImageAvailableListener {
    @Override
    public void onImageAvailable(ImageReader reader) {

        FileOutputStream fos = null;
        Bitmap bitmap = null;
        try (Image image = mImageReader.acquireLatestImage()) {
            if (image != null) {
                Image.Plane[] planes = image.getPlanes();
                ByteBuffer buffer = planes[0].getBuffer();
                int pixelStride = planes[0].getPixelStride();
                int rowStride = planes[0].getRowStride();
                int rowPadding = rowStride - pixelStride * mWidth;

                // create bitmap
                bitmap = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.ARGB_8888);
                bitmap.copyPixelsFromBuffer(buffer);

                // write bitmap to a file
                fos = new FileOutputStream(mStoreDir + "/myscreen_" + IMAGES_PRODUCED + ".png");
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);

                IMAGES_PRODUCED++;
                //Log.e(TAG, "captured image: " + IMAGES_PRODUCED);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }

            if (bitmap != null) {
                bitmap.recycle();
            }

        }
    }
}

Please give me an idea about this.

Thank you very much to everyone...

0

There are 0 answers