Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Remarque:Cette page fait référence au package Camera2. Nous vous recommandons d'utiliser CameraX, sauf si votre application nécessite des fonctionnalités spécifiques de base de Camera2. CameraX et Camera2 sont compatibles avec Android 5.0 (niveau d'API 21) ou version ultérieure.
Camera2 fournit une API Extensions pour accéder aux extensions que les fabricants d'appareils ont implémentées sur divers appareils Android. Pour obtenir la liste des modes d'extension compatibles, consultez Extensions Camera.
Pour obtenir la liste des appareils compatibles avec les extensions, consultez Appareils compatibles.
Architecture des extensions
L'image suivante illustre l'architecture des extensions Camera.
Figure 1. Architecture des extensions Camera
Une application Camera2 peut utiliser des extensions via l'API Camera2. Appareil photo 2
L'API fournit des moyens d'interroger les extensions disponibles, de configurer une extension
et communiquer avec la bibliothèque OEM d'extensions de caméra. Ce
permet à votre application d'utiliser des extensions telles que Nuit, HDR, Auto, Bokeh ou
Retouche du visage.
Tester la compatibilité d'un appareil photo avec l'API Extensions Camera2
L'extrait de code suivant vérifie si l'appareil est compatible avec la classe Camera2
API Extensions. Les extensions ne sont pas compatibles avec tous les appareils ou l'appareil peut être compatible avec un sous-ensemble
d'extensions. L'extrait de code renvoie une liste d'ID d'appareils photo compatibles
extensions pour appareil photo.
Créer une CameraExtensionSession avec l'API Camera2 Extensions
L'API Camera2 Extensions, lorsqu'elle est utilisée
avec des appareils compatibles, vous permet d'accéder
certaines extensions d'appareil photo. L'extrait de code suivant présente un exemple
comment créer un CameraExtensionSession
pour utiliser le mode de capture de nuit dans une application Camera2 existante.
Kotlin
privatevalcaptureCallbacks=object:CameraExtensionSession.ExtensionCaptureCallback(){// Implement Capture Callbacks}privatevalextensionSessionStateCallback=object:CameraExtensionSession.StateCallback(){overridefunonConfigured(session:CameraExtensionSession){cameraExtensionSession=sessiontry{valcaptureRequest=cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW).apply{addTarget(previewSurface)}.build()session.setRepeatingRequest(captureRequest,Dispatchers.IO.asExecutor(),captureCallbacks)}catch(e:CameraAccessException){Snackbar.make(previewView,"Failed to preview capture request",Snackbar.LENGTH_SHORT).show()requireActivity().finish()}}overridefunonClosed(session:CameraExtensionSession){super.onClosed(session)cameraDevice.close()}overridefunonConfigureFailed(session:CameraExtensionSession){Snackbar.make(previewView,"Failed to start camera extension preview",Snackbar.LENGTH_SHORT).show()requireActivity().finish()}}privatefunstartExtensionSession(){valoutputConfig=arrayListOf(OutputConfiguration(stillImageReader.surface),OutputConfiguration(previewSurface))valextensionConfiguration=ExtensionSessionConfiguration(CameraExtensionCharacteristics.EXTENSION_NIGHT,outputConfig,Dispatchers.IO.asExecutor(),extensionSessionStateCallback)cameraDevice.createExtensionSession(extensionConfiguration)}
Java
privateCameraExtensionSession.ExtensionCaptureCallbackcaptureCallbacks=newCameraExtensionSession.ExtensionCaptureCallback(){// Implement Capture Callbacks};privateCameraExtensionSession.StateCallbackextensionSessionStateCallback=newCameraExtensionSession.StateCallback(){@OverridepublicvoidonConfigured(@NonNullCameraExtensionSessionsession){cameraExtensionSession=session;try{CaptureRequest.BuildercaptureRequestBuilder=cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);captureRequestBuilder.addTarget(previewSurface);CaptureRequestcaptureRequest=captureRequestBuilder.build();session.setRepeatingRequest(captureRequest,backgroundExecutor,captureCallbacks);}catch(CameraAccessExceptione){Snackbar.make(previewView,"Failed to preview capture request",Snackbar.LENGTH_SHORT).show();requireActivity().finish();}}@OverridepublicvoidonClosed(@NonNullCameraExtensionSessionsession){super.onClosed(session);cameraDevice.close();}@OverridepublicvoidonConfigureFailed(@NonNullCameraExtensionSessionsession){Snackbar.make(previewView,"Failed to start camera extension preview",Snackbar.LENGTH_SHORT).show();requireActivity().finish();}};privatevoidstartExtensionSession(){ArrayList<OutputConfiguration>outputConfig=newArrayList<>();outputConfig.add(newOutputConfiguration(stillImageReader.getSurface()));outputConfig.add(newOutputConfiguration(previewSurface));ExtensionSessionConfigurationextensionConfiguration=newExtensionSessionConfiguration(CameraExtensionCharacteristics.EXTENSION_NIGHT,outputConfig,backgroundExecutor,extensionSessionStateCallback);}
Le contenu et les exemples de code de cette page sont soumis aux licences décrites dans la Licence de contenu. Java et OpenJDK sont des marques ou des marques déposées d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/07/27 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/07/27 (UTC)."],[],[],null,["# Camera2 Extensions API\n\n**Note:** This page refers to the [Camera2](/reference/android/hardware/camera2/package-summary) package. Unless your app requires specific, low-level features from Camera2, we recommend using [CameraX](/camerax). Both CameraX and Camera2 support Android 5.0 (API level 21) and higher.\n\n\u003cbr /\u003e\n\nCamera2 provides an Extensions API for accessing [extensions](/training/camera/camera-extensions) that device manufacturers have implemented on various Android devices. For a list of supported extension modes, see [Camera extensions](/training/camera/camera-extensions).\n\nFor a list of devices that support extensions, see [Supported devices](/training/camera/supported-devices).\n\nExtensions architecture\n-----------------------\n\nThe following image shows the camera extensions architecture.\n**Figure 1.**Camera Extensions architecture\n\nA Camera2 application can use extensions through the Camera2 API. The Camera2\nAPI provides ways to query for available extensions, configure an extension\ncamera session, and communicate with the Camera Extensions OEM library. This\nallows your application to use extensions like Night, HDR, Auto, Bokeh, or\nFace Retouch.\n\nTest a camera device for Camera2 Extensions API compatibility\n-------------------------------------------------------------\n\nThe following code snippet checks if the device supports the Camera2\nExtensions API. Extensions are not supported by all devices or the device might support a subset\nof extensions. The snippet returns a list of compatible camera IDs which support\ncamera extensions. \n\n### Kotlin\n\n```kotlin\nprivate fun getExtensionCameraIds(cameraManager: CameraManager): List\u003cString\u003e =\n if (Build.VERSION.SDK_INT \u003e= Build.VERSION_CODES.S) {\n cameraManager.cameraIdList.filter { cameraId -\u003e\n val characteristics = cameraManager.getCameraCharacteristics(cameraId)\n val extensionCharacteristics =\n cameraManager.getCameraExtensionCharacteristics(cameraId)\n val capabilities =\n characteristics.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES)\n extensionCharacteristics.supportedExtensions.isNotEmpty() &&\n capabilities?.contains(\n CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE\n ) ?: false\n }\n } else emptyList()\n```\n\n### Java\n\n```java\nprivate List\u003cString\u003e getExtensionCameraIds(CameraManager cameraManager)\n throws CameraAccessException {\n if (Build.VERSION.SDK_INT \u003e= Build.VERSION_CODES.S) {\n return Arrays.stream(cameraManager.getCameraIdList()).filter(cameraId -\u003e {\n try {\n CameraCharacteristics characteristics =\n cameraManager.getCameraCharacteristics(cameraId);\n CameraExtensionCharacteristics extensionCharacteristics =\n cameraManager.getCameraExtensionCharacteristics(cameraId);\n IntStream capabilities =\n Arrays.stream(\n characteristics.get(\n CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES\n )\n );\n return !extensionCharacteristics.getSupportedExtensions().isEmpty() &&\n capabilities.anyMatch(capability -\u003e capability == CameraCharacteristics\n .REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE\n );\n } catch (CameraAccessException e) {\n throw new RuntimeException(e);\n }\n }).collect(Collectors.toList());\n } else {\n return Collections.emptyList();\n }\n}\n```\n\nCreate a CameraExtensionSession with the Camera2 Extensions API\n---------------------------------------------------------------\n\nThe Camera2 Extensions API, when used with compatible devices, lets you access\ncertain camera extensions. The following code snippet showcases an example of\nhow to create a [`CameraExtensionSession`](https://developer.android.com/reference/android/hardware/camera2/CameraExtensionSession)\nfor using night capture mode for an existing Camera2 application. \n\n### Kotlin\n\n```kotlin\nprivate val captureCallbacks = object : CameraExtensionSession.ExtensionCaptureCallback() {\n // Implement Capture Callbacks\n}\nprivate val extensionSessionStateCallback = object : CameraExtensionSession.StateCallback() {\n override fun onConfigured(session: CameraExtensionSession) {\n cameraExtensionSession = session\n try {\n val captureRequest =\n cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW).apply {\n addTarget(previewSurface)\n }.build()\n session.setRepeatingRequest(\n captureRequest,\n Dispatchers.IO.asExecutor(),\n captureCallbacks\n )\n } catch (e: CameraAccessException) {\n Snackbar.make(\n previewView,\n \"Failed to preview capture request\",\n Snackbar.LENGTH_SHORT\n ).show()\n requireActivity().finish()\n }\n }\n\n override fun onClosed(session: CameraExtensionSession) {\n super.onClosed(session)\n cameraDevice.close()\n }\n\n override fun onConfigureFailed(session: CameraExtensionSession) {\n Snackbar.make(\n previewView,\n \"Failed to start camera extension preview\",\n Snackbar.LENGTH_SHORT\n ).show()\n requireActivity().finish()\n }\n}\n\nprivate fun startExtensionSession() {\n val outputConfig = arrayListOf(\n OutputConfiguration(stillImageReader.surface),\n OutputConfiguration(previewSurface)\n )\n val extensionConfiguration = ExtensionSessionConfiguration(\n CameraExtensionCharacteristics.EXTENSION_NIGHT,\n outputConfig,\n Dispatchers.IO.asExecutor(),\n extensionSessionStateCallback\n )\n cameraDevice.createExtensionSession(extensionConfiguration)\n}\n```\n\n### Java\n\n```java\nprivate CameraExtensionSession.ExtensionCaptureCallback captureCallbacks =\n new CameraExtensionSession.ExtensionCaptureCallback() {\n // Implement Capture Callbacks\n };\n\nprivate CameraExtensionSession.StateCallback extensionSessionStateCallback =\n new CameraExtensionSession.StateCallback() {\n @Override\n public void onConfigured(@NonNull CameraExtensionSession session) {\n cameraExtensionSession = session;\n try {\n CaptureRequest.Builder captureRequestBuilder =\n cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);\n captureRequestBuilder.addTarget(previewSurface);\n CaptureRequest captureRequest = captureRequestBuilder.build();\n session.setRepeatingRequest(captureRequest, backgroundExecutor, captureCallbacks);\n } catch (CameraAccessException e) {\n Snackbar.make(\n previewView,\n \"Failed to preview capture request\",\n Snackbar.LENGTH_SHORT\n ).show();\n requireActivity().finish();\n }\n }\n\n @Override\n public void onClosed(@NonNull CameraExtensionSession session) {\n super.onClosed(session);\n cameraDevice.close();\n }\n\n @Override\n public void onConfigureFailed(@NonNull CameraExtensionSession session) {\n Snackbar.make(\n previewView,\n \"Failed to start camera extension preview\",\n Snackbar.LENGTH_SHORT\n ).show();\n requireActivity().finish();\n }\n };\n\nprivate void startExtensionSession() {\n ArrayList\u003cOutputConfiguration\u003e outputConfig = new ArrayList\u003c\u003e();\n outputConfig.add(new OutputConfiguration(stillImageReader.getSurface()));\n outputConfig.add(new OutputConfiguration(previewSurface));\n ExtensionSessionConfiguration extensionConfiguration = new ExtensionSessionConfiguration(\n CameraExtensionCharacteristics.EXTENSION_NIGHT,\n outputConfig,\n backgroundExecutor,\n extensionSessionStateCallback\n );\n}\n```\n\nAdditional resources\n--------------------\n\nFor more information, see\n[`CameraExtensionCharacteristics`](/reference/android/hardware/camera2/CameraExtensionCharacteristics)\nand view the public [Camera2 Extensions API samples](https://github.com/android/camera-samples/tree/master/Camera2Extensions)\nfor more."]]