扣丁书屋

Android 使用 CameraX 实现拍照和录制视频

AndroidX是Jetpack包下的组件,谷歌帮你考虑好了很多细节,用就完事了。这些细节想自己设置的话也可以,不设置使用默认值照样很舒服。

导包

implementation "androidx.camera:camera-camera2:1.0.0-beta07"
implementation "androidx.camera:camera-view:1.0.0-alpha14"
implementation "androidx.camera:camera-extensions:1.0.0-alpha14"
implementation "androidx.camera:camera-lifecycle:1.0.0-beta07"

请求权限

Manifestmanifest 节点下中加入以下内容:

<!--摄像头权限-->
<uses-permission android:name="android.permission.CAMERA" />
<!--具备摄像头-->
<uses-feature android:name="android.hardware.camera.any" />
<!--存储图像或者视频权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--录制音频权限-->
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Android Q适配

manifest 标签里面加入一条属性:

 android:requestLegacyExternalStorage="true"

画黄线不理,如果不加这句,在Android Q上会无法往相册存储文件。

创建预览布局

这里参考官方Demo的写法,最底部图层是一个PreviewView用来预览,上层放两个按钮,一个用来拍照,一个用来录像。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnStartVideo"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginBottom="50dp"
        android:elevation="2dp"
        android:scaleType="fitCenter"
        android:text="Start Video"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/camera_capture_button" />

    <Button
        android:id="@+id/camera_capture_button"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:elevation="2dp"
        android:scaleType="fitCenter"
        android:text="Take Photo"
        app:layout_constraintBottom_toBottomOf="@+id/btnStartVideo"
        app:layout_constraintEnd_toStartOf="@id/btnStartVideo"
        app:layout_constraintStart_toStartOf="parent" />

    <androidx.camera.view.PreviewView
        android:id="@+id/viewFinder"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Activity中申请权限

声明权限列表

companion object {
    private const val REQUEST_CODE_PERMISSIONS = 10
    private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)
}

判断当前是否已有权限的方法

private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
    ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED
}

onCreate 里开始主要逻辑。如果已有权限,开启相机预览。

 if (allPermissionsGranted()) {
      startCamera()
} else {
      ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
}

在请求权限返回的时候,判断是否已有权限,如果有了就可以开启预览了

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
    if (requestCode == REQUEST_CODE_PERMISSIONS) {
        if (allPermissionsGranted()) {
            startCamera()
        } else {
            Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show()
            finish()
        }
    }
}

声明全局变量

private lateinit var cameraExecutor: ExecutorService
var cameraProvider: ProcessCameraProvider? = null//相机信息
var preview: Preview? = null//预览对象
var cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA//当前相机
var camera: Camera? = null//相机对象
private var imageCapture: ImageCapture? = null//拍照用例
var videoCapture: VideoCapture? = null//录像用例

开启相机预览

开启预览,把预览内容放进 PreviewView 里。

    private fun startCamera() {
        cameraExecutor = Executors.newSingleThreadExecutor()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            cameraProvider = cameraProviderFuture.get()//获取相机信息

            //预览配置
            preview = Preview.Builder()
                    .build()
                    .also {
                        it.setSurfaceProvider(viewFinder.createSurfaceProvider())
                    }

            imageCapture = ImageCapture.Builder().build()//拍照用例配置

            val imageAnalyzer = ImageAnalysis.Builder()
                    .build()
                    .also {
                        it.setAnalyzer(cameraExecutor, LuminosityAnalyzer { luma ->
                            Log.d(TAG, "Average luminosity: $luma")
                        })
                    }

            cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA//使用后置摄像头
            videoCapture = VideoCapture.Builder()//录像用例配置
//                .setTargetAspectRatio(AspectRatio.RATIO_16_9) //设置高宽比
//                .setTargetRotation(viewFinder.display.rotation)//设置旋转角度
//                .setAudioRecordSource(AudioSource.MIC)//设置音频源麦克风
                    .build()

            try {
                cameraProvider?.unbindAll()//先解绑所有用例
                camera = cameraProvider?.bindToLifecycle(this, cameraSelector, preview, imageCapture, videoCapture)//绑定用例
            } catch (exc: Exception) {
                Log.e(TAG, "Use case binding failed", exc)
            }

        }, ContextCompat.getMainExecutor(this))
    }

监听,写在Activity外面

typealias LumaListener = (luma: Double) -> Unit

再在Activity里面写一个内部类

private class LuminosityAnalyzer(private val listener: LumaListener) : ImageAnalysis.Analyzer {

        private fun ByteBuffer.toByteArray(): ByteArray {
            rewind()
            val data = ByteArray(remaining())
            get(data)
            return data
        }

        override fun analyze(image: ImageProxy) {

            val buffer = image.planes[0].buffer
            val data = buffer.toByteArray()
            val pixels = data.map { it.toInt() and 0xFF }
            val luma = pixels.average()

            listener(luma)

            image.close()
        }
    }

界面销毁时关闭线程

override fun onDestroy() {
    super.onDestroy()
    cameraExecutor.shutdown()
}

拍照方法

private fun takePhoto() {
    val imageCapture = imageCapture ?: return
    val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).path +
            "/CameraX" + SimpleDateFormat(FILENAME_FORMAT, Locale.CHINA).format(System.currentTimeMillis()) + ".jpg")
    val outputOptions = ImageCapture.OutputFileOptions.Builder(file).build()
    imageCapture.takePicture(outputOptions, ContextCompat.getMainExecutor(this),
            object : ImageCapture.OnImageSavedCallback {
                override fun onError(exc: ImageCaptureException) {
                    Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
                }
                override fun onImageSaved(output: ImageCapture.OutputFileResults) {
                    val savedUri = Uri.fromFile(file)
                    val msg = "Photo capture succeeded: $savedUri"
                    Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                    Log.d(TAG, msg)
                }
            })
}

录像方法

private fun takeVideo() {
    //视频保存路径
    val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).path + "/CameraX" + SimpleDateFormat(
            FILENAME_FORMAT, Locale.CHINA
    ).format(System.currentTimeMillis()) + ".mp4")
    //开始录像
    videoCapture?.startRecording(file, Executors.newSingleThreadExecutor(), object : OnVideoSavedCallback {
        override fun onVideoSaved(@NonNull file: File) {
            //保存视频成功回调,会在停止录制时被调用
            Toast.makeText(this@MainActivity, file.absolutePath, Toast.LENGTH_SHORT).show()
        }
        override fun onError(videoCaptureError: Int, message: String, cause: Throwable?) {
            //保存失败的回调,可能在开始或结束录制时被调用
            Log.e("", "onError: $message")
        }
    })


    btnStartVideo.setOnClickListener {
        //结束录像
        videoCapture?.stopRecording()//停止录制
        preview?.clear()//清除预览
        btnStartVideo.text = "Start Video"
        btnStartVideo.setOnClickListener {
            btnStartVideo.text = "Stop Video"
            takeVideo()
        }
        Toast.makeText(this, file.path, Toast.LENGTH_SHORT).show()
        Log.d("path", file.path)
    }
}

文中代码完整Demo

Github CameraX-Demo https://github.com/DubheBroken/CameraX-Demo

参考文章:

Google CameraX 开发文档 掘金-JetPack之使用CameraX完成拍照和拍视频 Stackoverflow-Exception 'open failed: EACCES (Permission denied)' on Android


https://mp.weixin.qq.com/s/B7VVEZ7LWr_XDCApcRtUTg

最多阅读

简化Android的UI开发 2年以前  |  515143次阅读
Android 深色模式适配原理分析 1年以前  |  26450次阅读
Android 样式系统 | 主题背景覆盖 1年以前  |  7989次阅读
Android Studio 生成so文件 及调用 1年以前  |  5631次阅读
30分钟搭建一个android的私有Maven仓库 3年以前  |  4777次阅读
Android设计与开发工作流 2年以前  |  4439次阅读
Google Enjarify:可代替dex2jar的dex反编译 3年以前  |  4420次阅读
Android多渠道打包工具:apptools 3年以前  |  4056次阅读
移动端常见崩溃指标 2年以前  |  4053次阅读
Google Java编程风格规范(中文版) 3年以前  |  3959次阅读
Android-模块化-面向接口编程 1年以前  |  3886次阅读
Android内存异常机制(用户空间)_NE 1年以前  |  3857次阅读
Android UI基本技术点 3年以前  |  3807次阅读
Android死锁初探 2年以前  |  3765次阅读

手机扫码阅读