CameraX предоставляет Extensions API для доступа к расширениям, которые производители устройств реализовали на различных устройствах Android, например "Ночная съемка", HDR, "Авто", "Боке" и "Ретушь лица". Список устройств, поддерживающих расширения, приведен в разделе Поддерживаемые устройства.
Архитектура расширений
На изображении ниже показана архитектура расширений камеры.
Приложение CameraX использует расширения через CameraX Extensions API. API запрашивает доступные расширения, настраивает сеанс расширения камеры и взаимодействует с реализацией расширений камеры устройства.
Как включить расширение
Чтобы включить расширение, выполните следующие действия:
- Получите экземпляр
ExtensionsManager. - Проверьте, доступен ли режим расширения для камеры с помощью
isExtensionAvailable(). Не все устройства поддерживают все режимы. - Создайте объект
ExtensionSessionConfigс режимом расширения и вариантами использованияPreviewиImageCapture. - Свяжите конфигурацию сеанса с
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, или настроите другие функции, убедитесь, что камера поддерживает всю комбинацию, прежде чем привязывать ее:
- Вызовите
isExtensionAvailable()с тем жеCameraSelectorи режимом. - Передайте
ExtensionSessionConfigвProcessCameraProvider.getCameraInfo(). Она возвращаетCameraInfoкамеры, которуюbindToLifecycle()привяжет для этой конфигурации. - Вызовите метод
isSessionConfigSupported()для этого объектаCameraInfo.
Если хотя бы одна из проверок не пройдена, привяжите обычный 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));
Как переключить или отключить расширение
Чтобы переключиться на другой режим расширения, снова вызовите bindToLifecycle() с новым ExtensionSessionConfig. Чтобы отключить расширения, свяжите обычный объект 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));
Улучшение процесса съемки
Некоторые режимы расширения, такие как Night и 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, получите CameraInfo камеры с поддержкой расширений с помощью getCameraInfo() и ExtensionSessionConfig, а затем проверьте, включает ли 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);
}
Предлагать ночной режим
Индикатор ночного режима сообщает приложению, что сцена достаточно темная, чтобы использовать расширение Night, и вы можете предложить пользователю переключиться на него. Индикатор показывается, когда камера работает без расширения. Проверьте поддержку с помощью CameraInfo.isNightModeIndicatorSupported(), а затем отслеживайте CameraInfo.getNightModeIndicator(). Если значение равно NightModeIndicator.RECOMMENDED, показать подсказку.
Если пользователь согласится, свяжите ExtensionSessionConfig с ExtensionMode.NIGHT.
Для индикатора ночного режима требуется CameraX 1.7.0 или более поздней версии и устройство с Android 16 (уровень API 36) или более поздней версии. isNightModeIndicatorSupported() возвращает false на более низких уровнях API.
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));
}
Связанные запросы
API расширений CameraX реализован в библиотеке 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}")
}
Яркий
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 можно найти в следующих ресурсах.
Практическая работа
Пример кода
Каталог примеров Camera (см. пример Extensions)
Другие справочные материалы
Расширения CameraX от поставщиков
Инструмент проверки расширений поставщиков CameraX