How can I capture camera preview frames with Jetpack Compose and CameraX

748 Views Asked by At

I'm trying to use CameraX with Jetpack Compose. I found a tutorial that shows how to put up the camera preview and take a picture. But I want to have my own preview so I can process the image first before showing it. I'm looking for help modifying the tutorial so that my own component gets called with an image that I can display. Then I can modify that image as necessary before displaying it.

Here is the code that puts up a built-in preview

@Composable
private fun CameraContent(
    onPhotoCaptured: (Bitmap) -> Unit,
    lastCapturedPhoto: Bitmap? = null
) {

    val context: Context = LocalContext.current
    val lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current
    val cameraController: LifecycleCameraController = remember { LifecycleCameraController(context) }

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        floatingActionButton = {
            ExtendedFloatingActionButton(
                text = { Text(text = "Take photo") },
                onClick = { capturePhoto(context, cameraController, onPhotoCaptured) },
                icon = { Icon(imageVector = Icons.Default.Camera, contentDescription = "Camera capture icon") }
            )
        }
    ) { paddingValues: PaddingValues ->

        Box(modifier = Modifier.fillMaxSize()) {
            AndroidView(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues),
                factory = { context ->
                    PreviewView(context).apply {
                        layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
                        setBackgroundColor(Color.BLACK)
                        implementationMode = PreviewView.ImplementationMode.COMPATIBLE
                        scaleType = PreviewView.ScaleType.FILL_START
                    }.also { previewView ->
                        previewView.controller = cameraController
                        cameraController.bindToLifecycle(lifecycleOwner)
                    }
                }
            )

            if (lastCapturedPhoto != null) {
                LastPhotoPreview(
                    modifier = Modifier.align(alignment = BottomStart),
                    lastCapturedPhoto = lastCapturedPhoto
                )
            }
        }
    }
}

From what I can tell, CameraX returns the old-style Android View that shows the camera stream images. I want my own composable function to handle the stream.

There doesn't seem to be much out there on using CameraX with Jetpack Compose. I'm new to Android native development and haven't learned the old XML view way of doing things. All the information seems to assume you are using CameraX with XML layouts.

0

There are 0 best solutions below