I am using Android ImageReader class to receive Bitmaps from MediaProjection.createVirtualDisplay method.
My code so far looks like this:
mProjectio
I encountered exactly your problem. My ImageReader created as so:
ImageReader.newInstance(mCaptureSize.getWidth(), mCaptureSize.getHeight(), ImageFormat.JPEG, 1);
The ImageReader above should only return compressed images, and these need to be decompressed. I acquireLatestImage(), then pass it through the following:
ByteBuffer bBuffer = planes[0].getBuffer;
bBuffer.rewind();
byte[] buffer = new byte[bBuffer.remaining()];
planes[0].getBuffer().get(buffer);
Bitmap bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
The key for me was to rewind the ByteBuffer. Your code should work as so:
mProjection.createVirtualDisplay("test", width, height, density, flags, mImageReader.getSurface(), new VirtualDisplayCallback(), mHandler);
mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
try {
image = mImageReader.acquireLatestImage();
final Image.Plane[] planes = image.getPlanes();
final ByteBuffer buffer = planes[0].getBuffer();
buffer.rewind()
final byte[] data = new byte[buffer.capacity()];
buffer.get(data);
final Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
if (bitmap==null)
Log.e(TAG, "bitmap is null");
} catch (Exception e) {
if (image!=null)
image.close();
}
}
}, mHandler);
I don't like having to copy the ByteBuffer through an intermediate byte[], but the internal array is protected.
Tested working on 5.0.1 on an HTC
I tested the code of the first answer, but unfortunately it does not work on real device. I make some investigation and the following code solved my problem:
mImgReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 5);
mSurface = mImgReader.getSurface();// mSurfaceView.getHolder().getSurface();
mImgReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Log.i(TAG, "in OnImageAvailable");
FileOutputStream fos = null;
Bitmap bitmap = null;
Image img = null;
try {
img = reader.acquireLatestImage();
if (img != null) {
Image.Plane[] planes = img.getPlanes();
if (planes[0].getBuffer() == null) {
return;
}
int width = img.getWidth();
int height = img.getHeight();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * width;
byte[] newData = new byte[width * height * 4];
int offset = 0;
bitmap = Bitmap.createBitmap(metrics,width, height, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = planes[0].getBuffer();
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
int pixel = 0;
pixel |= (buffer.get(offset) & 0xff) << 16; // R
pixel |= (buffer.get(offset + 1) & 0xff) << 8; // G
pixel |= (buffer.get(offset + 2) & 0xff); // B
pixel |= (buffer.get(offset + 3) & 0xff) << 24; // A
bitmap.setPixel(j, i, pixel);
offset += pixelStride;
}
offset += rowPadding;
}
String name = "/myscreen" + count + ".png";
count++;
File file = new File(Environment.getExternalStorageDirectory(), name);
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Log.i(TAG, "image saved in" + Environment.getExternalStorageDirectory() + name);
img.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != fos) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != bitmap) {
bitmap.recycle();
}
if (null != img) {
img.close();
}
}
}
}, mHandler);
Fo those of you looking for the easiest way to capture from ImageReader to a JPG (be it bytes on disk or in memory) It's actually quite simple.
Given an ImageReader, set it to ImageFormat.JPEG:
ImageReader imageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), imageFormat, 1);
Then in the CameraCaptureSession.StateCallback:
captureSession.capture(captureRequest, new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Image image = imageReader.acquireLatestImage();
final Image.Plane[] planes = image.getPlanes();
final ByteBuffer buffer = planes[0].getBuffer();
buffer.rewind();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
}
}
Then you have bytes
which you can do anything with. Send them over a socket, to a file, hash them, etc.
The code in answer by @charlesjean works but I would rather not generate each pixel by my self. A better way to get the Image from ImageReader is just to create right sized bitmap and use the method copyPixelsFromBuffer(). Create ImageReader as follows:
mImageReader = ImageReader.newInstance(mWidth, mHeight, ImageFormat.RGB_565, 2);
Then you can get the image from mImageReader using the code below.
final Image.Plane[] planes = image.getPlanes();
final ByteBuffer buffer = planes[0].getBuffer();
int offset = 0;
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.RGB_565);
bitmap.copyPixelsFromBuffer(buffer);
image.close();
I have described the process of capturing screen using MediaProjection API along with the mistakes most people made when getting image from ImageReader in a blog post which you can read if interested.
In case someone else stumbles on this, working code is as follows:
mImageReader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 5);
mProjection.createVirtualDisplay("test", width, height, density, flags, mImageReader.getSurface(), new VirtualDisplayCallback(), mHandler);
mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
FileOutputStream fos = null;
Bitmap bitmap = null;
try {
image = mImageReader.acquireLatestImage();
fos = new FileOutputStream(getFilesDir() + "/myscreen.jpg");
final Image.Plane[] planes = image.getPlanes();
final Buffer buffer = planes[0].getBuffer().rewind();
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
bitmap.compress(CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
if (image!=null)
image.close();
} finally {
if (fos!=null) {
try {
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bitmap!=null)
bitmap.recycle();
}
}
}, mHandler);
As you see I am saving the bitmap captured from ImageReader to a fileoutput stream and this produces a valid jpeg file.
The messages I was getting back from android_media_ImageReader.cpp were not indicating any sort of misbehaviour.
Hope it helps someone in the future!
I tried to use many example code. But none of those codes are working. I mixed those codes myself. And I created working sample code.
final DisplayMetrics dm = getResources().getDisplayMetrics();
mImageReader = ImageReader.newInstance(dm.widthPixels, dm.heightPixels, PixelFormat.RGBA_8888, 1);
mProjection.createVirtualDisplay("screen-mirror", dm.widthPixels, dm.heightPixels, dm.densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), vdCallback, mHandler);
mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = reader.acquireLatestImage();
if (image == null){
return;
}
final Image.Plane[] planes = image.getPlanes();
final ByteBuffer buffer = planes[0].getBuffer();
int offset = 0;
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * dm.widthPixels;
// create bitmap
Bitmap bitmap = Bitmap.createBitmap(dm.widthPixels+rowPadding/pixelStride, dm.heightPixels, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
imageView.setImageBitmap(bitmap);
image.close();
}
}, mHandler);