I'm trying to get a preview frame for QR code scanning functionality using Camera2 API. In old Camera API it's as easy as:
android.hardware.Camera mCamera;
...
mCamera.setPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
// will be invoked for every preview frame in addition to displaying them on the screen
}
});
However, I can't find a way to achieve that using new Camera2 API. I'd like to receive multiple frames that I can work on - the best would be to receive byte array as in old API. Any ideas how to do that?
For back-facing cameras, the sensor image buffer is rotated clockwise. The expression deviceOrientationDegrees * sign + 360 converts device rotation from counterclockwise to clockwise for back-facing cameras (for example, converting 270 degrees counterclockwise to 90 degrees clockwise).
PreviewView is a subclass of FrameLayout . To display the camera feed, it uses either a SurfaceView or TextureView , provides a preview surface to the camera when it's ready, tries to keep it valid as long as the camera is using it, and when released prematurely, provides a new surface if the camera is still in use.
Well, all you need to do is download a simple app called 'Camera2 API probe' from the Google Play Store and run it. The app gives detailed info about both the rear and front camera sensors of your Android phone. From that info, you can easily deduce whether your Android device supports Camera2 API or not.
A little late but better than never:
Usually a TextureView
is used to display the preview of the camera. You can use TextureView.SurfaceTextureListener
to get a callback every time the surface changes. TextureView
does provide a method getBitmap(Bitmap)
which you can use to get the preview frame in the same size as the TextureView
.
You can use this Google sample as starting point. Simply update the surfaceTextureListener like shown here:
private val surfaceTextureListener = object : TextureView.SurfaceTextureListener { override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) { openCamera(width, height) } override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) { configureTransform(width, height) } override fun onSurfaceTextureDestroyed(texture: SurfaceTexture) = true override fun onSurfaceTextureUpdated(texture: SurfaceTexture) { // Start changes // Get the bitmap val frame = Bitmap.createBitmap(textureView.width, textureView.height, Bitmap.Config.ARGB_8888) textureView.getBitmap(frame) // Do whatever you like with the frame frameProcessor?.processFrame(frame) // End changes } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With