我正在尝试使用 Camera2 API 获取预览框来进行QR码扫描功能。在旧的Camera API中,它很简单:

    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
        }
    });

但是,我无法找到使用新的 Camera2 API实现此目标的方法。我想接收多个可以处理的帧-最好是像旧API一样接收字节数组。任何想法如何做到这一点?

最佳答案

有点迟了,但是总比没有好:

通常,使用TextureView来显示摄像机的预览。每次表面变化时,都可以使用TextureView.SurfaceTextureListener获取回调。 TextureView确实提供了一种getBitmap(Bitmap)方法,您可以使用该方法获取与TextureView相同大小的预览帧。

您可以使用this Google sample作为起点。只需更新如下所示的surfaceTextureListener即可:

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
    }

}

10-08 07:00
查看更多