I use the Android ImageReader class to get bitmaps from the MediaProjection.createVirtualDisplay method.
My code looks like this:
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(); 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);
The problem is that BitmapFactory cannot decode data [] back to Bitmap, that is, BitmapFactory always returns null. The only messages I see from logcat relate to android_media_ImageReader.cpp and go as follows:
D/ImageReader_JNI(1432): ImageReader_imageSetup: Receiving JPEG in HAL_PIXEL_FORMAT_RGBA_8888 buffer. W/ImageReader_JNI(1432): Image_getJpegSize: No JPEG header detected, defaulting to size=width=3891200
The image object returned by the LatestImage retrieval method is not null, but is not a valid JPEG, I tried to check with the following test, which fails:
if((buf [0] & 0xFF) == 0xFF && (buf[1] & 0xFF) == 0xD8 && (buf[2] & 0xFF) == 0xFF && (buf[3] & 0xFF) == 0xE0) Log.e(TAG, "is JPG"); else Log.e(TAG, "not a valid JPG");
The only thing I suspect at the moment is that the Android 5.0 emulator I'm testing with cannot call API calls.
Any ideas?
android android-5.0-lollipop bitmap
mtsahakis
source share