音视频音视频开发

Android CameraX 详解三 (拍照)

2022-08-24  本文已影响0人  Kael_Zhang的安卓笔记

机票直达

Android CameraX 详解一 (引言&基础)
Android CameraX 详解二 (实时预览)
Android CameraX 详解三 (拍照)
Android CameraX 详解四 (图片分析)
Android CameraX 详解五(视频拍摄录制)

概述

拍照使用 ImageCapture 对象

图片拍摄用例旨在拍摄高分辨率的优质照片,不仅提供简单的相机手动控制功能,还提供自动白平衡、自动曝光和自动对焦 (3A) 功能。调用方负责决定如何使用拍摄的照片,具体包括以下选项:

运行 ImageCapture 的可自定义执行程序有两种类型:回调执行程序和 IO 执行程序

拍照步骤

<FrameLayout
    android:id="@+id/container">
        <androidx.camera.view.PreviewView
            android:id="@+id/previewView" />
</FrameLayout>
import androidx.camera.lifecycle.ProcessCameraProvider
import com.google.common.util.concurrent.ListenableFuture

class MainActivity : AppCompatActivity() {
    private lateinit var cameraProviderFuture : ListenableFuture<ProcessCameraProvider>
    override fun onCreate(savedInstanceState: Bundle?) {
        cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider = cameraProviderFuture.get()
            bindPreview(cameraProvider)
        }, ContextCompat.getMainExecutor(this))
    }
}
fun bindPreview(cameraProvider : ProcessCameraProvider) {
    val preview = Preview.Builder().build()
    val cameraSelector = CameraSelector.Builder()
          .requireLensFacing(CameraSelector.LENS_FACING_BACK)
          .build()
    val imageAnalyzer = ImageAnalysis.Builder().build()
    preview.setSurfaceProvider(previewView.getSurfaceProvider())
    imageCapture = ImageCapture.Builder().build()
    cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, imageCapture, imageAnalysis, preview)
}

// 拍照
val outputFileOptions = ImageCapture.OutputFileOptions.Builder(File(...)).build() 
imageCapture.takePicture(outputFileOptions, cameraExecutor,
    object : ImageCapture.OnImageSavedCallback {
        override fun onError(error: ImageCaptureException)
        {
             // insert your code here.
        }
        override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
             // insert your code here.
        }
})
上一篇下一篇

猜你喜欢

热点阅读