首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AndroidX本机相机

AndroidX本机相机
EN

Stack Overflow用户
提问于 2022-10-06 08:15:39
回答 1查看 72关注 0票数 0

我是android开发者的初学者,我试着使用CameraX。是否可以打开本机相机并拍照,而不是用预览和自定义按钮创建一个页面来拍照?我读过多篇文章/教程,但找不到解决方案。

谢谢你帮我

EN

回答 1

Stack Overflow用户

发布于 2022-10-06 11:37:27

使用示例这里,经过一些调整-我可以在没有任何预览的情况下拍摄一张照片。

首先,我们使用ImageCapture用例启动相机:

代码语言:javascript
复制
private fun startCamera() {
    val cameraProviderFuture = ProcessCameraProvider.getInstance(this)

    cameraProviderFuture.addListener({
        // Used to bind the lifecycle of cameras to the lifecycle owner
        val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

        imageCapture = ImageCapture.Builder()
            .build()
        // Select back camera as a default
        val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
        try {
            // Unbind use cases before rebinding
            cameraProvider.unbindAll()

            // Bind use cases to camera
            cameraProvider.bindToLifecycle(
                this, cameraSelector, imageCapture)
        } catch(exc: Exception) {
            Log.e("Error", "Use case binding failed", exc)
        }

    }, ContextCompat.getMainExecutor(this))
}

然后,我们可以通过调用takePhoto方法来拍照:

代码语言:javascript
复制
private fun takePhoto() {
    // Get a stable reference of the modifiable image capture use case
    val imageCapture = imageCapture ?: return

    // Create time stamped name and MediaStore entry.
    val contentValues = ContentValues().apply {
        put(MediaStore.MediaColumns.DISPLAY_NAME, "sample_image")
        put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
            put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/CameraX-Image")
        }
    }

    // Create output options object which contains file + metadata
    val outputOptions = ImageCapture.OutputFileOptions
        .Builder(contentResolver,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            contentValues)
        .build()

    // Set up image capture listener, which is triggered after photo has
    // been taken
    imageCapture.takePicture(
        outputOptions,
        ContextCompat.getMainExecutor(this),
        object : ImageCapture.OnImageSavedCallback {
            override fun onError(exc: ImageCaptureException) {
                Log.e("Error", "Photo capture failed: ${exc.message}", exc)
            }

            override fun
                    onImageSaved(output: ImageCapture.OutputFileResults){
                val msg = "Photo capture succeeded: ${output.savedUri}"
                Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                Log.d("Success", msg)
            }
        }
    )
}

我已经把一个工作项目上传到Github

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73970592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档