Implement a preview

The preview use case produces a SurfaceTexture which streams the camera input. It also provides additional information for a View to crop, scale, or rotate for proper display.

The image preview is streamed to this SurfaceTexture when the camera becomes active. The SurfaceTexture can be connected to a TextureView or a GLSurfaceView.

Implementation

The following sample shows how to use PreviewOutput:

Kotlin

val previewConfig = PreviewConfig.Builder().build()
val preview = Preview(previewConfig)

preview.setOnPreviewOutputUpdateListener {
    previewOutput: Preview.PreviewOutput? ->
        // Your code here. For example, use previewOutput?.getSurfaceTexture()
        // and post to a GL renderer.
}

CameraX.bindToLifecycle(this as LifecycleOwner, preview)

Java

PreviewConfig config = new PreviewConfig.Builder().build();
Preview preview = new Preview(config);

preview.setOnPreviewOutputUpdateListener(
    new Preview.OnPreviewOutputUpdateListener() {
        @Override
        public void onUpdated(Preview.PreviewOutput previewOutput) {
            // Your code here. For example, use previewOutput.getSurfaceTexture()
            // and post to a GL renderer.
    });
});

CameraX.bindToLifecycle((LifecycleOwner) this, preview);

Additional resources

To learn more about CameraX, consult the following additional resources.

Codelab

  • Getting Started with CameraX
  • Code sample

  • Official CameraX sample app