CameraX 擴充功能 API

CameraX 提供 Extensions API,可用於存取裝置製造商在不同 Android 裝置上實作的擴充功能,例如「夜晚」、「高動態範圍」、「自動」、「散景」和「修容」。如需支援擴充功能的裝置清單,請參閱「支援的裝置」。

擴充功能架構

下圖顯示相機擴充功能的架構。

CameraX 應用程式會使用 CameraX Extensions 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() 啟用後檢視,再進行繫結。如果相機不支援後置預覽,就不會產生後置預覽圖片。繫結後,請使用 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,請呼叫 setExtensionStrength(),並傳遞 0 到 100 之間的值。如果值為 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,則顯示建議。如果使用者接受,請使用 ExtensionMode.NIGHT 繫結 ExtensionSessionConfig。

夜間模式指標需要 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 廠商擴充功能驗證工具