我试图使用前置摄像头捕捉图片。但我得到错误:-相机镜头面对验证失败,现有的相机。
我也无法得到预览的相机以及。这里是代码:-
@ExperimentalPermissionsApi
class MainActivity : ComponentActivity() {
@OptIn(ExperimentalCoilApi::class, ExperimentalCoroutinesApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
OP2Theme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
MainContent(Modifier.fillMaxSize())
}
}
}
}
}
@ExperimentalCoilApi
@ExperimentalCoroutinesApi
@ExperimentalPermissionsApi
@Composable
fun MainContent(modifier: Modifier = Modifier) {
val emptyImageUri = Uri.parse("file://dev/null")
var imageUri by remember { mutableStateOf(emptyImageUri) }
if (imageUri != emptyImageUri) {
Box(modifier = modifier) {
Image(
modifier = Modifier.fillMaxSize(),
painter = rememberImagePainter(imageUri),
contentDescription = "Captured image"
)
Button(
modifier = Modifier.align(Alignment.BottomCenter),
onClick = {
imageUri = emptyImageUri
}
) {
Text("Remove image")
}
}
} else {
CameraCapture(
modifier = modifier,
onImageFile = { file ->
imageUri = file.toUri()
}
)
}
}
@Composable
fun Greeting(name: String) {
Text(text = "Hello $name!")
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
OP2Theme {
Greeting("Android")
}
}
这里是相机预览的代码:-
@Composable
fun CameraPreview(
modifier: Modifier = Modifier,
scaleType: PreviewView.ScaleType = PreviewView.ScaleType.FILL_CENTER,
onUseCase: (UseCase) -> Unit = { }
) {
AndroidView(
modifier = modifier,
factory = { context ->
val previewView = PreviewView(context).apply {
this.scaleType = scaleType
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}
onUseCase(
Preview.Builder()
.build()
.also {
it.setSurfaceProvider(previewView.surfaceProvider)
}
)
previewView
}
)
}
这是我的代码相机捕捉:
@ExperimentalPermissionsApi
@ExperimentalCoroutinesApi
@Composable
fun CameraCapture(
modifier: Modifier = Modifier,
cameraSelector: CameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA,
onImageFile: (File) -> Unit = { }
) {
val context = LocalContext.current
Permission(
permission = Manifest.permission.CAMERA,
rationale = "You said you wanted a picture, so I'm going to have to ask for permission.",
permissionNotAvailableContent = {
Column(modifier) {
Text("O noes! No Camera!")
Spacer(modifier = Modifier.height(8.dp))
Button(
onClick = {
context.startActivity(
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = Uri.fromParts("package", context.packageName, null)
}
)
}
) {
Text("Open Settings")
}
}
}
) {
Box(modifier = modifier) {
val lifecycleOwner = LocalLifecycleOwner.current
val coroutineScope = rememberCoroutineScope()
var previewUseCase by remember { mutableStateOf<UseCase>(Preview.Builder().build()) }
val imageCaptureUseCase by remember {
mutableStateOf(
ImageCapture.Builder()
.setCaptureMode(CAPTURE_MODE_MAXIMIZE_QUALITY)
.build()
)
}
Box {
CameraPreview(
modifier = Modifier.fillMaxSize(),
onUseCase = {
previewUseCase = it
}
)
Button(
modifier = Modifier
.wrapContentSize()
.padding(16.dp)
.align(Alignment.BottomCenter),
onClick = {
coroutineScope.launch {
imageCaptureUseCase.takePicture(context.executor).let {
onImageFile(it)
}
}
}
) {
Text("Click!")
}
}
LaunchedEffect(previewUseCase) {
val cameraProvider = context.getCameraProvider()
try {
// Must unbind the use-cases before rebinding them.
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(
lifecycleOwner, cameraSelector, previewUseCase, imageCaptureUseCase
)
} catch (ex: Exception) {
Log.e("CameraCapture", "Failed to bind camera use cases", ex)
}
}
}
}
}
下面是我的权限代码:-
@ExperimentalPermissionsApi
@Composable
fun Permission(
permission: String = android.Manifest.permission.CAMERA,
rationale: String = "This permission is important for this app. Please grant the permission.",
permissionNotAvailableContent: @Composable () -> Unit = { },
content: @Composable () -> Unit = { }
) {
val permissionState = rememberPermissionState(permission)
PermissionRequired(
permissionState = permissionState,
permissionNotGrantedContent = {
Rationale(
text = rationale,
onRequestPermission = { permissionState.launchPermissionRequest() }
)
},
permissionNotAvailableContent = permissionNotAvailableContent,
content = content
)
}
@Composable
private fun Rationale(
text: String,
onRequestPermission: () -> Unit
) {
AlertDialog(
onDismissRequest = { /* Don't */ },
title = {
Text(text = "Permission request")
},
text = {
Text(text)
},
confirmButton = {
Button(onClick = onRequestPermission) {
Text("Ok")
}
}
)
}
Build.gradle中camerax的依赖关系:-
//Camera
def camerax_version = "1.2.1"
//noinspection GradleDependency
implementation "androidx.camera:camera-camera2:$camerax_version"
implementation "androidx.camera:camera-lifecycle:$camerax_version"
implementation "androidx.camera:camera-view:1.3.0-alpha03"
清单.xml中的权限:-
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
这些是我在使用此代码时遇到的错误。:-
E/CameraValidator: Camera LensFacing verification failed, existing cameras: [Camera@af090c1[id=0], Camera@743c9c0[id=1]]
E/CameraX: The device might underreport the amount of the cameras. Finish the initialize task since we are already reaching the maximum number of retries.
E/CameraCapture: Failed to bind camera use cases
java.lang.IllegalArgumentException: Provided camera selector unable to resolve a camera for the given use case
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:479)
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:366)
at com.op2.files.CameraCaptureKt$CameraCapture$3$1$2.invokeSuspend(CameraCapture.kt:110)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at androidx.compose.ui.platform.AndroidUiDispatcher.performTrampolineDispatch(AndroidUiDispatcher.android.kt:81)
at androidx.compose.ui.platform.AndroidUiDispatcher.access$performTrampolineDispatch(AndroidUiDispatcher.android.kt:41)
at androidx.compose.ui.platform.AndroidUiDispatcher$dispatchCallback$1.run(AndroidUiDispatcher.android.kt:57)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8751)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
E/CameraCapture: Failed to bind camera use cases
java.lang.IllegalArgumentException: Provided camera selector unable to resolve a camera for the given use case
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:479)
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:366)
at com.op2.files.CameraCaptureKt$CameraCapture$3$1$2.invokeSuspend(CameraCapture.kt:110)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at androidx.compose.ui.platform.AndroidUiDispatcher.performTrampolineDispatch(AndroidUiDispatcher.android.kt:81)
at androidx.compose.ui.platform.AndroidUiDispatcher.access$performTrampolineDispatch(AndroidUiDispatcher.android.kt:41)
at androidx.compose.ui.platform.AndroidUiDispatcher$dispatchCallback$1.run(AndroidUiDispatcher.android.kt:57)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8751)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
I/ViewRootImpl@9e9624a[MainActivity]: ViewPostIme pointer 0
I/ViewRootImpl@9e9624a[MainActivity]: ViewPostIme pointer 1
D/ImageCapture: takePictureWithNode
E/TakePicture: Image capture failed
androidx.camera.core.ImageCaptureException: Not bound to a valid Camera [ImageCapture:androidx.camera.core.ImageCapture-b7455703-bb88-40b0-b3da-acfd633286f6]
at androidx.camera.core.ImageCapture.sendInvalidCameraError(ImageCapture.java:1725)
at androidx.camera.core.ImageCapture.takePictureWithNode(ImageCapture.java:1706)
at androidx.camera.core.ImageCapture.takePicture(ImageCapture.java:918)
at com.op2.files.ExtKt.takePicture(ext.kt:43)
at com.op2.files.ExtKt$takePicture$1.invokeSuspend(Unknown Source:13)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at androidx.compose.ui.platform.AndroidUiDispatcher.performTrampolineDispatch(AndroidUiDispatcher.android.kt:81)
at androidx.compose.ui.platform.AndroidUiDispatcher.access$performTrampolineDispatch(AndroidUiDispatcher.android.kt:41)
at androidx.compose.ui.platform.AndroidUiDispatcher$dispatchCallback$1.run(AndroidUiDispatcher.android.kt:57)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8751)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.op2, PID: 5120
androidx.camera.core.ImageCaptureException: Not bound to a valid Camera [ImageCapture:androidx.camera.core.ImageCapture-b7455703-bb88-40b0-b3da-acfd633286f6]
at androidx.camera.core.ImageCapture.sendInvalidCameraError(ImageCapture.java:1725)
at androidx.camera.core.ImageCapture.takePictureWithNode(ImageCapture.java:1706)
at androidx.camera.core.ImageCapture.takePicture(ImageCapture.java:918)
at com.op2.files.ExtKt.takePicture(ext.kt:43)
at com.op2.files.ExtKt$takePicture$1.invokeSuspend(Unknown Source:13)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at androidx.compose.ui.platform.AndroidUiDispatcher.performTrampolineDispatch(AndroidUiDispatcher.android.kt:81)
at androidx.compose.ui.platform.AndroidUiDispatcher.access$performTrampolineDispatch(AndroidUiDispatcher.android.kt:41)
at androidx.compose.ui.platform.AndroidUiDispatcher$dispatchCallback$1.run(AndroidUiDispatcher.android.kt:57)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8751)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [androidx.compose.ui.platform.MotionDurationScaleImpl@6183a1, androidx.compose.runtime.BroadcastFrameClock@f2649c6, StandaloneCoroutine{Cancelling}@2ebed87, AndroidUiDispatcher@e3d74b4]
2条答案
按热度按时间iih3973s1#
您正在使用不同版本的camerax_version,请使用相同版本。
在build. gradle中进行以下更改。:-
axr492tv2#
该错误可能与缺少摄像机权限、摄像机配置或硬件问题有关。
要解决此问题,您可以先检查您在AndroidManifest.xml文件中是否具有正确的相机权限。请确保您已包含以下权限:
您还应该检查您正在使用的设备是否有前置摄像头。有些设备没有前置摄像头,尝试访问它将导致错误。