首页 > 解决方案 > Kotlin CameraX 无法捕获图像

问题描述

我想使用 CameraX 库捕获图像并保存到文件中。我捕获了图像并保存。图像文件的大小为 0B。我不知道我哪里出错了。日志说这个错误:

    androidx.camera.core.ImageCaptureException: Not bound to a valid Camera [ImageCapture:androidx.camera.core.ImageCapture-52180692-0099-40c3-8d17-508e08019b84] 

这是我的捕获代码:

fun bindPreview(
    lifecycleOwner: LifecycleOwner,
    previewView: PreviewView,
    cameraProvider: ProcessCameraProvider,
){
    val preview = Preview.Builder()
        .build().also {
            it.setSurfaceProvider(previewView.surfaceProvider)
        }

     imageCapture = ImageCapture.Builder().build()

    val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

    try {
      cameraProvider.unbindAll()

      cameraProvider.bindToLifecycle(
            lifecycleOwner, cameraSelector, preview, imageCapture)
    }catch(exception: Exception) {
        Log.e(TAG, "Use case binding failed", exception)
    }

}

fun onImageCaptureClicked(context: Context){
        outputDirectory = getOutputDirectory(context)

        val photoFile = File(outputDirectory,  SimpleDateFormat(FILENAME_FORMAT, Locale.US
        ).format(System.currentTimeMillis()) + ".jpg")

        val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()

        imageCapture.takePicture(
            outputOptions, ContextCompat.getMainExecutor(context), object :ImageCapture.OnImageSavedCallback{
                override fun onError(exception: ImageCaptureException) {
                    Log.e( TAG, "Photo capture failed: ${exception.message}", exception)
                }
                override fun onImageSaved(output: ImageCapture.OutputFileResults) {
                    val savedUri = Uri.fromFile(photoFile)
                    val msg = "Photo capture succeeded: $savedUri"
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                    Log.d(TAG, msg)
                }
            }
        )
}

我应该怎么办?

标签: androidkotlinandroid-camerax

解决方案


推荐阅读