CameraX Extensions API

CameraX 提供了一个 Extensions API,用于访问设备制造商在各种 Android 设备上实现的扩展,例如夜间、HDR、自动、焦外成像和美颜。如需查看支持扩展的设备列表,请参阅支持的设备。

扩展架构

下图显示了相机扩展程序架构。

CameraX 应用使用 CameraX Extensions API,该 API 会与设备的相机扩展实现进行通信。
图 1. 相机扩展架构

CameraX 应用通过 CameraX Extensions API 使用扩展。该 API 会查询哪些扩展程序可用,配置扩展程序相机会话,并与设备的相机扩展程序实现进行通信。

启用扩展程序

如需启用扩展程序,请执行以下操作:

  1. 获取 ExtensionsManager 实例。
  2. 使用 isExtensionAvailable() 检查扩展模式是否适用于相机。并非所有设备都支持所有模式。
  3. 使用扩展模式以及 Preview 和 ImageCapture 用例创建 ExtensionSessionConfig。
  4. 使用 ProcessCameraProvider.bindToLifecycle() 绑定会话配置。扩展模式会应用于 Preview 和 ImageCapture 用例。

Kotlin

suspend fun bindNightMode(
    context: Context,
    lifecycleOwner: LifecycleOwner,
    surfaceProvider: Preview.SurfaceProvider,
) {
    val cameraProvider = ProcessCameraProvider.awaitInstance(context)
    val extensionsManager =
        ExtensionsManager.getInstance(context, cameraProvider)
    val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

    // Not every device supports every mode, and binding a mode that the
    // camera doesn't support fails. Check availability first.
    val isNightAvailable = extensionsManager.isExtensionAvailable(
        cameraSelector, ExtensionMode.NIGHT
    )
    if (!isNightAvailable) {
        // Bind a regular session instead (not shown) so that the camera
        // still works on devices without the Night extension.
        return
    }

    val preview = Preview.Builder().build()
    preview.setSurfaceProvider(surfaceProvider)
    val imageCapture = ImageCapture.Builder().build()

    // The session config ties the extension mode to the use cases, so
    // CameraX applies Night mode to both Preview and ImageCapture.
    val sessionConfig = ExtensionSessionConfig(
        ExtensionMode.NIGHT,
        extensionsManager,
        preview,
        imageCapture,
    )

    cameraProvider.bindToLifecycle(
        lifecycleOwner, cameraSelector, sessionConfig
    )
}

Java

void bindNightMode(Context context, LifecycleOwner lifecycleOwner,
        Preview.SurfaceProvider surfaceProvider) {
    Executor mainExecutor = ContextCompat.getMainExecutor(context);
    ListenableFuture<ProcessCameraProvider> providerFuture =
            ProcessCameraProvider.getInstance(context);

    // Both the camera provider and ExtensionsManager initialize
    // asynchronously. Bind only after both are ready.
    providerFuture.addListener(() -> {
        try {
            ProcessCameraProvider cameraProvider = providerFuture.get();
            ListenableFuture<ExtensionsManager> managerFuture =
                    ExtensionsManager.getInstanceAsync(
                            context, cameraProvider);
            managerFuture.addListener(() -> {
                try {
                    bindNightModeSession(managerFuture.get(),
                            cameraProvider, lifecycleOwner,
                            surfaceProvider);
                } catch (ExecutionException | InterruptedException e) {
                    Log.e(TAG, "Failed to get ExtensionsManager", e);
                }
            }, mainExecutor);
        } catch (ExecutionException | InterruptedException e) {
            Log.e(TAG, "Failed to get the camera provider", e);
        }
    }, mainExecutor);
}

void bindNightModeSession(ExtensionsManager extensionsManager,
        ProcessCameraProvider cameraProvider,
        LifecycleOwner lifecycleOwner,
        Preview.SurfaceProvider surfaceProvider) {
    CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;

    // Not every device supports every mode, and binding a mode that the
    // camera doesn't support fails. Check availability first.
    if (!extensionsManager.isExtensionAvailable(
            cameraSelector, ExtensionMode.NIGHT)) {
        // Bind a regular session instead (not shown) so that the camera
        // still works on devices without the Night extension.
        return;
    }

    Preview preview = new Preview.Builder().build();
    preview.setSurfaceProvider(surfaceProvider);
    ImageCapture imageCapture = new ImageCapture.Builder().build();

    // The session config ties the extension mode to the use cases, so
    // CameraX applies Night mode to both Preview and ImageCapture.
    ExtensionSessionConfig sessionConfig = new ExtensionSessionConfig(
            ExtensionMode.NIGHT, extensionsManager, preview, imageCapture);

    cameraProvider.bindToLifecycle(
            lifecycleOwner, cameraSelector, sessionConfig);
}

支持的使用场景

下表显示了在启用扩展程序的情况下可以绑定的用例:

使用场景 启用扩展程序
Preview、ImageCapture 支持。应用扩展程序模式。
VideoCapture 支持。VideoCapture 会记录共享的 Preview 流。
ImageAnalysis 不受支持。

检查相机是否支持会话配置

如果您添加了更多用例(例如 VideoCapture)或设置了其他功能,请在绑定之前检查相机是否支持整个组合:

  1. 使用相同的 CameraSelector 和模式调用 isExtensionAvailable()。
  2. 将 ExtensionSessionConfig 传递给 ProcessCameraProvider.getCameraInfo()。它会返回 bindToLifecycle() 将为该配置绑定的相机的 CameraInfo。
  3. 对该 CameraInfo 调用 isSessionConfigSupported()。

如果任一检查失败,请改为绑定常规 SessionConfig。

Kotlin

fun createSessionConfig(
    mode: Int,
    vararg useCases: UseCase,
): SessionConfig {
    // getCameraInfo() throws if no camera matches the extension, so check
    // that the mode is available first.
    if (extensionsManager.isExtensionAvailable(cameraSelector, mode)) {
        val extensionConfig =
            ExtensionSessionConfig(mode, extensionsManager, *useCases)
        // Check the camera that would actually be bound for this config,
        // and verify that it supports these use cases together with the
        // extension, for example VideoCapture.
        if (cameraProvider.getCameraInfo(cameraSelector, extensionConfig)
                .isSessionConfigSupported(extensionConfig)
        ) {
            return extensionConfig
        }
    }
    // The same use cases can still run in a regular session, so the app
    // keeps working without the extension.
    return SessionConfig(*useCases)
}

cameraProvider.bindToLifecycle(
    lifecycleOwner,
    cameraSelector,
    createSessionConfig(
        ExtensionMode.NIGHT, preview, imageCapture, videoCapture
    ),
)

Java

SessionConfig createSessionConfig(int mode, UseCase... useCases) {
    // getCameraInfo() throws if no camera matches the extension, so check
    // that the mode is available first.
    if (extensionsManager.isExtensionAvailable(cameraSelector, mode)) {
        ExtensionSessionConfig extensionConfig =
                new ExtensionSessionConfig(
                        mode, extensionsManager, useCases);
        // Check the camera that would actually be bound for this config,
        // and verify that it supports these use cases together with the
        // extension, for example VideoCapture.
        if (cameraProvider.getCameraInfo(cameraSelector, extensionConfig)
                .isSessionConfigSupported(extensionConfig)) {
            return extensionConfig;
        }
    }
    // The same use cases can still run in a regular session, so the app
    // keeps working without the extension.
    return new SessionConfig(useCases);
}

cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector,
        createSessionConfig(
                ExtensionMode.NIGHT, preview, imageCapture, videoCapture));

切换或停用扩展程序

如需切换到其他扩展模式,请使用新的 ExtensionSessionConfig 再次调用 bindToLifecycle()。如需停用扩展程序,请将常规 SessionConfig 与相同的用例绑定。您无需先调用 unbind() 或 unbindAll():之前绑定的会话配置及其用例会自动解除绑定。

Kotlin

// Binding a new session config unbinds the previous one and its use
// cases, so you don't need to call unbindAll() before switching modes.
cameraProvider.bindToLifecycle(
    lifecycleOwner,
    cameraSelector,
    ExtensionSessionConfig(
        ExtensionMode.NIGHT, extensionsManager, preview, imageCapture
    ),
)

// A regular SessionConfig with the same use cases turns the extension off
// while Preview and ImageCapture keep working.
cameraProvider.bindToLifecycle(
    lifecycleOwner,
    cameraSelector,
    SessionConfig(preview, imageCapture),
)

Java

// Binding a new session config unbinds the previous one and its use
// cases, so you don't need to call unbindAll() before switching modes.
cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector,
        new ExtensionSessionConfig(ExtensionMode.NIGHT,
                extensionsManager, preview, imageCapture));

// A regular SessionConfig with the same use cases turns the extension off
// while Preview and ImageCapture keep working.
cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector,
        new SessionConfig(preview, imageCapture));

改进拍摄体验

某些扩展程序模式(例如夜间模式和 HDR)可能需要几秒钟才能处理完静态图片。为了让用户在等待期间了解进度,请在设备支持的情况下使用预览和拍摄进度:

  • Postview 会提前提供低分辨率图片,您可以在最终图片准备就绪之前显示该图片。
  • 拍摄处理进度会报告 0 到 100 的处理进度,您可以将其显示为进度指示器。

在绑定之前,请先使用 ImageCapture.Builder.setPostviewEnabled() 启用浏览后转化。如果相机不支持 postview,则不会生成 postview 图片。 绑定后,将 ImageCapture.getImageCaptureCapabilities() 与所绑定相机的 CameraInfo 搭配使用,以检查 isPostviewSupported() 和 isCaptureProcessProgressSupported(),并设置界面以进行匹配。

Kotlin

// Postview must be configured before binding. If the camera doesn't
// support postview, enabling it has no effect.
val imageCapture = ImageCapture.Builder()
    .setPostviewEnabled(true)
    .build()

val camera = cameraProvider.bindToLifecycle(
    lifecycleOwner,
    cameraSelector,
    ExtensionSessionConfig(
        ExtensionMode.NIGHT, extensionsManager, preview, imageCapture
    ),
)

// Postview and progress support depend on the extension-enabled camera,
// so query the capabilities of the bound camera.
val capabilities =
    ImageCapture.getImageCaptureCapabilities(camera.cameraInfo)
setUpCaptureUi(
    showPostview = capabilities.isPostviewSupported,
    showProgress = capabilities.isCaptureProcessProgressSupported,
)

// Extension captures can take several seconds. Progress updates and an
// early postview image show users that the capture is being processed.
val results = imageCapture.takePicture(
    outputFileOptions,
    onCaptureProcessProgressed = { progress -> updateProgress(progress) },
    onPostviewBitmapAvailable = { bitmap -> showPostview(bitmap) },
)
// Processing is done. Replace the postview with the final image.
showFinalImage(results.savedUri)

Java

// Postview must be configured before binding. If the camera doesn't
// support postview, enabling it has no effect.
ImageCapture imageCapture = new ImageCapture.Builder()
        .setPostviewEnabled(true)
        .build();

Camera camera = cameraProvider.bindToLifecycle(
        lifecycleOwner, cameraSelector,
        new ExtensionSessionConfig(ExtensionMode.NIGHT,
                extensionsManager, preview, imageCapture));

// Postview and progress support depend on the extension-enabled camera,
// so query the capabilities of the bound camera.
ImageCaptureCapabilities capabilities =
        ImageCapture.getImageCaptureCapabilities(camera.getCameraInfo());
setUpCaptureUi(
        capabilities.isPostviewSupported(),
        capabilities.isCaptureProcessProgressSupported());

// Extension captures can take several seconds. Progress updates and an
// early postview image show users that the capture is being processed.
imageCapture.takePicture(outputFileOptions, mainExecutor,
        new ImageCapture.OnImageSavedCallback() {
            @Override
            public void onCaptureProcessProgressed(int progress) {
                updateProgress(progress);
            }

            @Override
            public void onPostviewBitmapAvailable(@NonNull Bitmap bitmap) {
                showPostview(bitmap);
            }

            @Override
            public void onImageSaved(
                    @NonNull ImageCapture.OutputFileResults results) {
                // Processing is done. Replace the postview with the final
                // image.
                showFinalImage(results.getSavedUri());
            }

            @Override
            public void onError(@NonNull ImageCaptureException exception) {
                Log.e(TAG, "Capture failed", exception);
            }
        });

拍摄 Ultra HDR 图片

某些设备支持在启用扩展程序时拍摄 Ultra HDR 图片。必须在绑定之前设置输出格式,如果格式不受支持,绑定会失败。因此,请先检查是否支持:在 isExtensionAvailable() 返回 true 后,使用 getCameraInfo() 和 ExtensionSessionConfig 获取启用了扩展程序的相机的 CameraInfo,然后检查 getSupportedOutputFormats() 是否包含 OUTPUT_FORMAT_JPEG_ULTRA_HDR。

Kotlin

// Supported output formats can differ when an extension is enabled, so
// query them from the extension-enabled camera. isExtensionAvailable()
// must have returned true for this selector and mode first; otherwise,
// getCameraInfo() throws.
val extensionCameraInfo = cameraProvider.getCameraInfo(
    cameraSelector,
    ExtensionSessionConfig(ExtensionMode.NIGHT, extensionsManager),
)
val supportedFormats = ImageCapture
    .getImageCaptureCapabilities(extensionCameraInfo)
    .supportedOutputFormats

// Binding fails if the output format isn't supported, so request Ultra HDR
// only when the extension-enabled camera supports it.
val imageCapture = ImageCapture.Builder().apply {
    if (ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR in supportedFormats) {
        setOutputFormat(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)
    }
}.build()

cameraProvider.bindToLifecycle(
    lifecycleOwner,
    cameraSelector,
    ExtensionSessionConfig(
        ExtensionMode.NIGHT, extensionsManager, preview, imageCapture
    ),
)

Java

// Supported output formats can differ when an extension is enabled, so
// query them from the extension-enabled camera. isExtensionAvailable()
// must have returned true for this selector and mode first; otherwise,
// getCameraInfo() throws.
CameraInfo extensionCameraInfo = cameraProvider.getCameraInfo(
        cameraSelector,
        new ExtensionSessionConfig(ExtensionMode.NIGHT, extensionsManager));
Set<Integer> supportedFormats =
        ImageCapture.getImageCaptureCapabilities(extensionCameraInfo)
                .getSupportedOutputFormats();

// Binding fails if the output format isn't supported, so request Ultra HDR
// only when the extension-enabled camera supports it.
ImageCapture.Builder builder = new ImageCapture.Builder();
if (supportedFormats.contains(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)) {
    builder.setOutputFormat(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR);
}
ImageCapture imageCapture = builder.build();

cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector,
        new ExtensionSessionConfig(ExtensionMode.NIGHT,
                extensionsManager, preview, imageCapture));

监控和调整扩展程序

绑定后,将 ExtensionsManager.getCameraExtensionsInfo() 和 ExtensionsManager.getCameraExtensionsControl() 与绑定的相机搭配使用,以监控和调整扩展程序。

调整扩展强度

如果 isExtensionStrengthAvailable() 返回 true,请使用 0 到 100 之间的值调用 setExtensionStrength()。值为 0 表示不应用扩展处理,默认值为 100。强度控制的内容取决于模式;例如,在夜间模式下,它控制融合的图片数量以及最终图片的亮度。观察 getExtensionStrength() 以获取当前值。

Kotlin

val camera = cameraProvider.bindToLifecycle(
    lifecycleOwner,
    cameraSelector,
    ExtensionSessionConfig(
        ExtensionMode.NIGHT, extensionsManager, preview, imageCapture
    ),
)
// Pass the bound extension-enabled camera. For a camera without an
// extension, strength isn't available and the control is null.
val extensionsInfo =
    extensionsManager.getCameraExtensionsInfo(camera.cameraInfo)
val extensionsControl =
    extensionsManager.getCameraExtensionsControl(camera.cameraControl)

// Not every device lets apps adjust the strength, so check support before
// showing a strength control.
if (extensionsInfo.isExtensionStrengthAvailable) {
    // For example, connect this to a slider in your UI.
    extensionsControl?.setExtensionStrength(50)
}

Java

Camera camera = cameraProvider.bindToLifecycle(
        lifecycleOwner, cameraSelector,
        new ExtensionSessionConfig(ExtensionMode.NIGHT,
                extensionsManager, preview, imageCapture));
// Pass the bound extension-enabled camera. For a camera without an
// extension, strength isn't available and the control is null.
CameraExtensionsInfo extensionsInfo =
        extensionsManager.getCameraExtensionsInfo(camera.getCameraInfo());
CameraExtensionsControl extensionsControl =
        extensionsManager.getCameraExtensionsControl(
                camera.getCameraControl());

// Not every device lets apps adjust the strength, so check support before
// showing a strength control.
if (extensionsInfo.isExtensionStrengthAvailable()
        && extensionsControl != null) {
    // For example, connect this to a slider in your UI.
    extensionsControl.setExtensionStrength(50);
}

显示当前扩展程序模式

ExtensionMode.AUTO 可以根据场景切换到夜间或 HDR 等模式。如果 isCurrentExtensionModeAvailable() 返回 true,请观察 getCurrentExtensionMode(),向用户显示哪种模式处于活动状态。

Kotlin

val camera = cameraProvider.bindToLifecycle(
    lifecycleOwner,
    cameraSelector,
    ExtensionSessionConfig(
        ExtensionMode.AUTO, extensionsManager, preview, imageCapture
    ),
)
val extensionsInfo =
    extensionsManager.getCameraExtensionsInfo(camera.cameraInfo)

// In AUTO mode, the active mode can change with the scene, for example to
// NIGHT in low light. The LiveData is null when the device doesn't report
// the current mode.
if (extensionsInfo.isCurrentExtensionModeAvailable) {
    extensionsInfo.currentExtensionMode?.observe(lifecycleOwner) { mode ->
        showActiveModeBadge(mode)
    }
}

Java

Camera camera = cameraProvider.bindToLifecycle(
        lifecycleOwner, cameraSelector,
        new ExtensionSessionConfig(ExtensionMode.AUTO,
                extensionsManager, preview, imageCapture));
CameraExtensionsInfo extensionsInfo =
        extensionsManager.getCameraExtensionsInfo(camera.getCameraInfo());

// In AUTO mode, the active mode can change with the scene, for example to
// NIGHT in low light. The LiveData is null when the device doesn't report
// the current mode.
LiveData<Integer> currentMode = extensionsInfo.getCurrentExtensionMode();
if (extensionsInfo.isCurrentExtensionModeAvailable()
        && currentMode != null) {
    currentMode.observe(lifecycleOwner, this::showActiveModeBadge);
}

建议使用夜间模式

夜间模式指示器会告知应用场景何时足够暗,以便夜间扩展程序提供帮助,这样您就可以建议用户切换到该扩展程序。当相机在不使用扩展程序的情况下运行时,系统会报告该指示器。使用 CameraInfo.isNightModeIndicatorSupported() 检查支持情况,然后观察 CameraInfo.getNightModeIndicator()。当值为 NightModeIndicator.RECOMMENDED 时,显示建议。 如果用户接受,请将 ExtensionSessionConfig 与 ExtensionMode.NIGHT 绑定。

夜间模式指示器需要 CameraX 1.7.0 或更高版本,以及搭载 Android 16(API 级别 36)或更高版本的设备。isNightModeIndicatorSupported() 在较低 API 级别上返回 false。

Kotlin

// The indicator is reported while a regular (non-extension) session is
// running with Preview, so the app can suggest Night mode only when the
// scene is dark enough to need it.
val cameraInfo = camera.cameraInfo

// Don't suggest a mode that the camera can't bind.
val isNightAvailable = extensionsManager.isExtensionAvailable(
    cameraSelector, ExtensionMode.NIGHT
)

// If the indicator isn't supported, its value is always UNKNOWN.
if (cameraInfo.isNightModeIndicatorSupported && isNightAvailable) {
    cameraInfo.nightModeIndicator.observe(lifecycleOwner) { indicator ->
        showNightModeSuggestion(
            visible = indicator == NightModeIndicator.RECOMMENDED
        )
    }
}

fun onNightModeSuggestionAccepted() {
    // Binding the extension session config replaces the regular session.
    cameraProvider.bindToLifecycle(
        lifecycleOwner,
        cameraSelector,
        ExtensionSessionConfig(
            ExtensionMode.NIGHT, extensionsManager, preview, imageCapture
        ),
    )
}

Java

// The indicator is reported while a regular (non-extension) session is
// running with Preview, so the app can suggest Night mode only when the
// scene is dark enough to need it.
CameraInfo cameraInfo = camera.getCameraInfo();

// Don't suggest a mode that the camera can't bind.
boolean isNightAvailable = extensionsManager.isExtensionAvailable(
        cameraSelector, ExtensionMode.NIGHT);

// If the indicator isn't supported, its value is always UNKNOWN.
if (cameraInfo.isNightModeIndicatorSupported() && isNightAvailable) {
    cameraInfo.getNightModeIndicator().observe(lifecycleOwner,
            indicator -> showNightModeSuggestion(
                    indicator == NightModeIndicator.RECOMMENDED));
}

void onNightModeSuggestionAccepted() {
    // Binding the extension session config replaces the regular session.
    cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector,
            new ExtensionSessionConfig(ExtensionMode.NIGHT,
                    extensionsManager, preview, imageCapture));
}

依赖项

CameraX Extensions API 是在 camera-extensions 库中实现的。这些扩展依赖于 CameraX 核心模块(core、camera2 和 lifecycle)。请为所有 androidx.camera 库使用同一版本。

Kotlin

dependencies {
    val camerax_version = "1.7.0"
    implementation("androidx.camera:camera-core:${camerax_version}")
    implementation("androidx.camera:camera-camera2:${camerax_version}")
    implementation("androidx.camera:camera-lifecycle:${camerax_version}")
    // The CameraX Extensions library
    implementation("androidx.camera:camera-extensions:${camerax_version}")
}

Groovy

dependencies {
    def camerax_version = "1.7.0"
    implementation "androidx.camera:camera-core:${camerax_version}"
    implementation "androidx.camera:camera-camera2:${camerax_version}"
    implementation "androidx.camera:camera-lifecycle:${camerax_version}"
    // The CameraX Extensions library
    implementation "androidx.camera:camera-extensions:${camerax_version}"
}

从已废弃的相机选择器 API 迁移

ExtensionsManager.getExtensionEnabledCameraSelector() 自 CameraX 1.7.0-alpha02 起已废弃。请改用 ExtensionSessionConfig,如下表所示:

已弃用 替换
getExtensionEnabledCameraSelector(cameraSelector, mode) ExtensionSessionConfig(mode, extensionsManager, useCases)
bindToLifecycle(owner, extensionCameraSelector, preview, imageCapture) bindToLifecycle(owner, cameraSelector, extensionSessionConfig)
getCameraInfo(extensionCameraSelector) getCameraInfo(cameraSelector, extensionSessionConfig)
unbindAll(),然后重新绑定以切换模式 绑定新的会话配置。之前的绑定会自动解除。

其他资源

如需详细了解 CameraX,请参阅以下资源。

Codelab

  • CameraX 使用入门
  • 代码示例

    相机示例目录(请参阅 Extensions 示例)

    其他参考

    CameraX 供应商扩展程序

    CameraX 供应商扩展程序验证工具