在Android中使用CameraX處理多攝像頭時,你可以采用以下步驟:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.front" />
接下來,在你的Activity或Fragment中,通過以下代碼獲取CameraManager實例:
val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
val cameraIds: Array<String> = cameraManager.cameraIdList
val primaryCameraId = cameraIds[0]
val cameraSelector = CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build()
val preview = Preview.Builder().build()
val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
cameraProviderFuture.addListener({
val cameraProvider = cameraProviderFuture.get()
bindPreview(cameraProvider, cameraSelector, preview)
}, ContextCompat.getMainExecutor(context))
private fun bindPreview(cameraProvider: ProcessCameraProvider, cameraSelector: CameraSelector, preview: Preview) {
val previewView = ImageView(context).also {
it.layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}
val cameraSelector = cameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build()
val imageAnalyzer = ImageAnalyzerBuilder().build()
val cameraCaptureSession = cameraProvider.unbindAll()
cameraCaptureSession?.close()
cameraProvider.bindToLifecycle(
this, cameraSelector, preview, imageAnalyzer, cameraCaptureSession
)
preview.setSurfaceProvider(previewView.surfaceProvider)
}
private val imageAnalyzer = ImageAnalyzerBuilder().build()
override fun onImageAnalysis(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image
if (mediaImage != null) {
// 處理圖像數據,例如顯示在ImageView中或保存到本地
// ...
imageProxy.close()
}
}
通過以上步驟,你可以在Android中使用CameraX處理多攝像頭。請注意,這里的代碼示例是用Kotlin編寫的,但你可以根據需要將其轉換為Java。