Reputation: 5193
I have a app with the following layout
All I want to do is take a picture / snapshot of this and looking into it, seem bonkers / complex
I first took a snapshot of the SurfaceView and got a black square, it appears this method is incorrect
Now I am using MediaProjection / ImageReader?
Update : So I do get a image but of wavy lines and it crashes because I am trying to stop the MediaProjection. As said all I want to do is take a single picture
private void saveImage()
{
final Handler mHandler = new Handler();
final ImageReader mImageReader = ImageReader.newInstance(cameraSurface.getWidth(), cameraSurface.getHeight(), PixelFormat.RGBA_8888, 2);
mProjection.createVirtualDisplay("screen-mirror", cameraSurface.getWidth(), cameraSurface.getHeight(), mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null);
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(Environment.getExternalStorageDirectory().toString() + "/myscreen.jpg");
final Image.Plane[] planes = image.getPlanes();
final Buffer buffer = planes[0].getBuffer().rewind();
bitmap = Bitmap.createBitmap(cameraSurface.getWidth(), cameraSurface.getHeight(), Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
//MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Title" , "Desc");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos!=null) {
try {
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bitmap!=null)
bitmap.recycle();
if (image!=null)
image.close();
if (mProjection!=null) {
mProjection.stop();
mImageReader.close();
}
}
}
}, mHandler);
}
Upvotes: 0
Views: 540
Reputation: 52353
You're configuring your ImageReader for ImageFormat.RGB_565, which is format 0x4. The virtual display is returning frames in format 0x1, PixelFormat.RGBA_8888. (Yes, there are two overlapping definitions of color format.) The configurations don't match, hence the error.
Change your ImageReader creation line to use the RGBA_8888 format instead.
You will have another issue when you try to create the Bitmap. decodeByteArray()
is meant for compressed data, such as PNG or JPEG. It won't know how to interpret raw pixel data. Use a call like Bitmap#createBitmap() instead, passing ARGB_8888 in the Bitmap.Config parameter.
(For some more general commentary, see this answer.)
Upvotes: 2