Android 5.0对拍照API进行了全新的设计,新增了全新设计的Camera 2 API,这些API不仅大幅提高了Android系统拍照的功能,还能支持RAW照片输出,甚至允许程序调整相机的对焦模式、曝光模式、快门等;
一、Camera2架构介绍
Camera2引用了管道的概念将安卓设备和摄像头之间联通起来,系统向摄像头发送 Capture 请求,而摄像头会返回 CameraMetadata。这一切建立在一个叫作 CameraCaptureSession 的会话中;
架构在核心参与类角色有:CameraManager、CameraDevice、CameraCharacteristics、CameraRequest与CameraRequest.Builder、CameraCaptureSession以及CaptureResult;
1、CameraManager
位于android.hardware.camera2.CameraManager下,也是Android 21(5.0)添加的,和其他系统服务一样通过 Context.getSystemService(CameraManager.class ) 或者Context.getSystemService(Context.CAMERA_SERVICE) 来完成初始化,主要用于管理系统摄像头:
- 通过getCameraIdList()方法获取Android设备的摄像头列表;
- getCameraCharacteristics(String cameraId)获取摄像头的详细参数和支持的功能;
2、CameraDevice
- CameraDevice是Camera2中抽象出来的一个对象,直接与系统硬件摄像头相联系;
- 即摄像头功能可被分为limit 和full 两个级别,当摄像头处于limited 级别时候,此时Camera2和早期的Camera功能差不多,除此之外在Camera2架构中,CameraDevice还承担其他重要任务:
- 通过CameraDevice.StateCallback监听摄像头的状态(主要包括onOpened、onClosed、onDisconnected、onErro四种状态);
- 管理CameraCaptureSession,-通过方法createCaptureSession()方法和createReprocessableCaptureSession()方法创建会话 ,通常会在CameraDevice.StateCallback中调用对应方法创建预览会话;
- 管理CaptureRequest,主要包括通过createCaptureRequest(int templateType)创建捕获请求,在需要预览、拍照、再次预览的时候都需要通过创建请求来完成;
3、CameraCaptureSession
- 系统向摄像头发送 Capture 请求,而摄像头会返回 CameraMetadata,这一切都是在由对应的CameraDevice创建的CameraCaptureSession 会话完成,当程序需要预览、拍照、再次预览时,都需要先通过会话;
- CameraCaptureSession的有很多重要回调:
- 管理CameraCaptureSession.StateCallback状态回调,用于接收有关CameraCaptureSession状态的更新的回调对象;
- 管理CameraCaptureSession.CaptureCallback捕获回调,用于接收捕获请求状态的回调,当请求触发捕获已启动时;捕获完成时;在捕获图像时发生错误的情况下;都会触发该回调对应的方法;
- 通过调用方法capture()提交捕获图像请求即拍照,其中该请求定义了捕获单个图像的所有参数,包括传感器,镜头,闪光灯和后处理参数,每一次请求的结果将产生一个CaptureResult,可以为一个或多个Surface生成新的帧,然后通过CaptureRequest.Builder的addTarget(Surface)方法附着到对应的Surface上显示;
- 通过调用方法setRepeatingRequest()请求不断重复捕获图像,即实现预览;
- 通过方法调用stopRepeating()实现停止捕获图像,即停止预览;
4、CameraCharacteristics
描述Cameradevice属性的对象,可以使用CameraManager通过getCameraCharacteristics(String cameraId)进行查询;
5、CameraRequest和CameraRequest.Builder
CameraRequest代表了一次捕获请求,而CameraRequest.Builder用于描述捕获图片的各种参数设置,包含捕获硬件(传感器,镜头,闪存),对焦模式、曝光模式,处理流水线,控制算法和输出缓冲区的配置,然后传递到对应的会话中进行设置,CameraRequest.Builder则负责生成CameraRequest对象。当程序调用setRepeatingRequest()方法进行预览时,或调用capture()方法进行拍照时,都需要传入CameraRequest参数。CameraRequest可以通过CameraRequest.Builder来进行初始化,通过调用createCaptureRequest来获得;
6、CaptureResult
CaptureRequest描述是从图像传感器捕获单个图像的结果的子集的对象,当CaptureRequest被处理之后由CameraDevice生成;
7、Camera2 主要角色之间的联系
CameraManager处于顶层管理位置负责检测获取所有摄像头及其特性和传入指定的CameraDevice.StateCallback回调打开指定摄像头,CameraDevice是负责管理抽象对象,包括监听Camera 的状态回调CameraDevice.StateCallback、创建CameraCaptureSession和CameraRequest;
二、Camera2 相机开发流程详解
1、申请权限
name="android.permission.CAMERA" /> name ="android.permission.WRITE_EXTERNAL_STORAGE" />
2、在xml布局文件中定义一个TextureView
- android:id="@+id/textureView"
- android:layout_width="match_parent"
- android:layout_height="match_parent" />
3、创建一个CameraHelper类,并给TextureView对象添加回调函数
- class Camera2Helper(val mActivity: Activity, private val mTextureView: TextureView) {
- companion object {
- const val PREVIEW_WIDTH = 720 //预览的宽度
- const val PREVIEW_HEIGHT = 1280 //预览的高度
- const val SAVE_WIDTH = 720 //保存图片的宽度
- const val SAVE_HEIGHT = 1280 //保存图片的高度
- }
- private lateinit var mCameraManager: CameraManager
- private var mImageReader: ImageReader? = null
- private var mCameraDevice: CameraDevice? = null
- private var mCameraCaptureSession: CameraCaptureSession? = null
- private var mCameraId = "0"
- private lateinit var mCameraCharacteristics: CameraCharacteristics
- private var mCameraSensorOrientation = 0 //摄像头方向
- private var mCameraFacing = CameraCharacteristics.LENS_FACING_BACK //默认使用后置摄像头
- private val mDisplayRotation = mActivity.windowManager.defaultDisplay.rotation //手机方向
- private var canTakePic = true //是否可以拍照
- private var canExchangeCamera = false //是否可以切换摄像头
- private var mCameraHandler: Handler
- private val handlerThread = HandlerThread("CameraThread")
- private var mPreviewSize = Size(PREVIEW_WIDTH, PREVIEW_HEIGHT) //预览大小
- private var mSavePicSize = Size(SAVE_WIDTH, SAVE_HEIGHT) //保存图片大小
- init {
- handlerThread.start()
- mCameraHandler = Handler(handlerThread.looper)
- mTextureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
- override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture?, width: Int, height: Int) {
- }
- override fun onSurfaceTextureUpdated(surface: SurfaceTexture?) {
- }
- override fun onSurfaceTextureDestroyed(surface: SurfaceTexture?): Boolean {
- releaseCamera()
- return true
- }
- override fun onSurfaceTextureAvailable(surface: SurfaceTexture?, width: Int, height: Int) {
- initCameraInfo()
- }
- }
- }
- }
- 打开相机和创建会话等都是耗时操作,所以我们启动一个HandlerThread在子线程中来处理;
- 有两个关于尺寸的变量,一个是预览尺寸(在屏幕上显示),一个是保存图片的尺寸(保存到sd卡中图片的尺寸);
- 有两个方向,一个是手机方向(如果是竖屏应用的话此方向为0),另一个是摄像头方向(一般来说,前置摄像头方向为270,后置摄像头方向为90);
4、初始化相关参数
-
- private fun initCameraInfo() {
- mCameraManager = mActivity.getSystemService(Context.CAMERA_SERVICE) as CameraManager
- val cameraIdList = mCameraManager.cameraIdList
- if (cameraIdList.isEmpty()) {
- mActivity.toast("没有可用相机")
- return
- }
- for (id in cameraIdList) {
- val cameraCharacteristics = mCameraManager.getCameraCharacteristics(id)
- val facing = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING)
- if (facing == mCameraFacing) {
- mCameraId = id
- mCameraCharacteristics = cameraCharacteristics
- }
- log("设备中的摄像头 $id")
- }
- val supportLevel = mCameraCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)
- if (supportLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
- mActivity.toast("相机硬件不支持新特性")
- }
- //获取摄像头方向
- mCameraSensorOrientation = mCameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)
- //获取StreamConfigurationMap,它是管理摄像头支持的所有输出格式和尺寸
- val configurationMap = mCameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
- val savePicSize = configurationMap.getOutputSizes(ImageFormat.JPEG) //保存照片尺寸
- val previewSize = configurationMap.getOutputSizes(SurfaceTexture::class.java) //预览尺寸
- val exchange = exchangeWidthAndHeight(mDisplayRotation, mCameraSensorOrientation)
- mSavePicSize = getBestSize(
- if (exchange) mSavePicSize.height else mSavePicSize.width,
- if (exchange) mSavePicSize.width else mSavePicSize.height,
- if (exchange) mSavePicSize.height else mSavePicSize.width,
- if (exchange) mSavePicSize.width else mSavePicSize.height,
- savePicSize.toList())
- mPreviewSize = getBestSize(
- if (exchange) mPreviewSize.height else mPreviewSize.width,
- if (exchange) mPreviewSize.width else mPreviewSize.height,
- if (exchange) mTextureView.height else mTextureView.width,
- if (exchange) mTextureView.width else mTextureView.height,
- previewSize.toList())
- mTextureView.surfaceTexture.setDefaultBufferSize(mPreviewSize.width, mPreviewSize.height)
- log("预览最优尺寸 :${mPreviewSize.width} * ${mPreviewSize.height}, 比例 ${mPreviewSize.width.toFloat() / mPreviewSize.height}")
- log("保存图片最优尺寸 :${mSavePicSize.width} * ${mSavePicSize.height}, 比例 ${mSavePicSize.width.toFloat() / mSavePicSize.height}")
- //根据预览的尺寸大小调整TextureView的大小,保证画面不被拉伸
- val orientation = mActivity.resources.configuration.orientation
- if (orientation == Configuration.ORIENTATION_LANDSCAPE)
- mTextureView.setAspectRatio(mPreviewSize.width, mPreviewSize.height)
- else
- mTextureView.setAspectRatio(mPreviewSize.height, mPreviewSize.width)
- mImageReader = ImageReader.newInstance(mPreviewSize.width, mPreviewSize.height, ImageFormat.JPEG, 1)
- mImageReader?.setOnImageAvailableListener(onImageAvailableListener, mCameraHandler)
- if (openFaceDetect)
- initFaceDetect()
- openCamera()
- }
-
- private fun exchangeWidthAndHeight(displayRotation: Int, sensorOrientation: Int): Boolean {
- var exchange = false
- when (displayRotation) {
- Surface.ROTATION_0, Surface.ROTATION_180 ->
- if (sensorOrientation == 90 || sensorOrientation == 270) {
- exchange = true
- }
- Surface.ROTATION_90, Surface.ROTATION_270 ->
- if (sensorOrientation == 0 || sensorOrientation == 180) {
- exchange = true
- }
- else -> log("Display rotation is invalid: $displayRotation")
- }
- log("屏幕方向 $displayRotation")
- log("相机方向 $sensorOrientation")
- return exchange
- }
-
- private fun getBestSize(targetWidth: Int, targetHeight: Int, maxWidth: Int, maxHeight: Int, sizeList: List<Size>): Size {
- val bigEnough = ArrayList<Size>() //比指定宽高大的Size列表
- val notBigEnough = ArrayList<Size>() //比指定宽高小的Size列表
- for (size in sizeList) {
- //宽<=最大宽度 && 高<=最大高度 && 宽高比 == 目标值宽高比
- if (size.width <= maxWidth && size.height <= maxHeight
- && size.width == size.height * targetWidth / targetHeight) {
- if (size.width >= targetWidth && size.height >= targetHeight)
- bigEnough.add(size)
- else
- notBigEnough.add(size)
- }
- log("系统支持的尺寸: ${size.width} * ${size.height} , 比例 :${size.width.toFloat() / size.height}")
- }
- log("最大尺寸 :$maxWidth * $maxHeight, 比例 :${targetWidth.toFloat() / targetHeight}")
- log("目标尺寸 :$targetWidth * $targetHeight, 比例 :${targetWidth.toFloat() / targetHeight}")
- //选择bigEnough中最小的值 或 notBigEnough中最大的值
- return when {
- bigEnough.size > 0 -> Collections.min(bigEnough, CompareSizesByArea())
- notBigEnough.size > 0 -> Collections.max(notBigEnough, CompareSizesByArea())
- else -> sizeList[0]
- }
- }
- 首先,通过mActivity.getSystemService(Context.CAMERA_SERVICE) as CameraManager 获取到 CameraManager 实例;
- 通过循环遍历设备中可用的相机,通过 mCameraManager.getCameraCharacteristics(id) 获取到相机的各种信息;
- mCameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) 获取到相机传感器的方向;
- 通过 configurationMap.getOutputSizes(ImageFormat.JPEG) 和 configurationMap.getOutputSizes(SurfaceTexture::class.java) 获取到相机支持的预览尺寸和保存图片的尺寸;
- exchangeWidthAndHeight(displayRotation: Int, sensorOrientation: Int)方法的作用是根据屏幕方向和摄像头方向确定是否需要交换宽高;
- 通过 getBestSize() 方法获取到最优的宽和高。根据传入的 目标宽高值、最大宽高值(即屏幕大小)和 相机支持的尺寸列表,从相机支持的尺寸列表中得到一个最优值;
- 通过mTextureView.surfaceTexture.setDefaultBufferSize() 方法用来设置TextureView的预览尺寸;
- 创建一个ImageReader对象,并设置回调函数;
- 在onImageAvailableListener中处理得到的图像数据;
5、打开相机
-
- private fun openCamera() {
- if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
- mActivity.toast("没有相机权限!")
- return
- }
- mCameraManager.openCamera(mCameraId, object : CameraDevice.StateCallback() {
- override fun onOpened(camera: CameraDevice) {
- log("onOpened")
- mCameraDevice = camera
- createCaptureSession(camera)
- }
- override fun onDisconnected(camera: CameraDevice) {
- log("onDisconnected")
- }
- override fun onError(camera: CameraDevice, error: Int) {
- log("onError $error")
- mActivity.toast("打开相机失败!$error")
- }
- }, mCameraHandler)
- }
6、创建预览会话
-
- private fun createCaptureSession(cameraDevice: CameraDevice) {
- val captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
- val surface = Surface(mTextureView.surfaceTexture)
- captureRequestBuilder.addTarget(surface) // 将CaptureRequest的构建器与Surface对象绑定在一起
- captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH) // 闪光灯
- captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE) // 自动对焦
- // 为相机预览,创建一个CameraCaptureSession对象
- cameraDevice.createCaptureSession(arrayListOf(surface, mImageReader?.surface), object : CameraCaptureSession.StateCallback() {
- override fun onConfigureFailed(session: CameraCaptureSession?) {
- mActivity.toast("开启预览会话失败!")
- }
- override fun onConfigured(session: CameraCaptureSession) {
- mCameraCaptureSession = session
- session.setRepeatingRequest(captureRequestBuilder.build(), mCaptureCallBack, mCameraHandler)
- }
- }, mCameraHandler)
- }
- private val mCaptureCallBack = object : CameraCaptureSession.CaptureCallback() {
- override fun onCaptureCompleted(session: CameraCaptureSession, request: CaptureRequest?, result: TotalCaptureResult) {
- super.onCaptureCompleted(session, request, result)
- canExchangeCamera = true
- canTakePic = true
- }
- override fun onCaptureFailed(session: CameraCaptureSession?, request: CaptureRequest?, failure: CaptureFailure?) {
- super.onCaptureFailed(session, request, failure)
- log("onCaptureFailed")
- mActivity.toast("开启预览失败!")
- }
- }
- 通过cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW) 创建一个用于预览的Builder对象;
- 为该Builder对象添加一个Surface对象,并设置各种相关参数;
- 通过cameraDevice.createCaptureSession创建一个会话,第一个参数中传了一个 surface 和 mImageReader?.surface。这表明了这次会话的图像数据的输出到这两个对象;
- 当会话创建成功时,通过 session.setRepeatingRequest(captureRequestBuilder.build(), mCaptureCallBack, mCameraHandler) 发起预览请求;
7、拍照、保存
-
- fun takePic() {
- if (mCameraDevice == null || !mTextureView.isAvailable || !canTakePic) return
- mCameraDevice?.apply {
- val captureRequestBuilder = createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE)
- captureRequestBuilder.addTarget(mImageReader?.surface)
- captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE) // 自动对焦
- captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH) // 闪光灯
- captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, mCameraSensorOrientation) //根据摄像头方向对保存的照片进行旋转,使其为"自然方向"
- mCameraCaptureSession?.capture(captureRequestBuilder.build(), null, mCameraHandler)
- ?: mActivity.toast("拍照异常!")
- }
- }
- private val onImageAvailableListener = OnImageAvailableListener {
- val image = it.acquireNextImage()
- val byteBuffer = image.planes[0].buffer
- val byteArray = ByteArray(byteBuffer.remaining())
- byteBuffer.get(byteArray)
- it.close()
- BitmapUtils.savePic(byteArray, mCameraSensorOrientation == 270, { savedPath, time ->
- mActivity.runOnUiThread {
- mActivity.toast("图片保存成功!保存路径:$savedPath 耗时:$time")
- }
- }, { msg ->
- mActivity.runOnUiThread {
- mActivity.toast("图片保存失败!$msg")
- }
- })
- }
- 通过createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE) 创建一个拍照请求的Builder对象;
- 然后设置各种参数。注意,captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, mCameraSensorOrientation)用来设置保存照片的旋转方向。如果不设置的话,保存的照片不是"自然方向";
- 拍照的结果是在 OnImageAvailableListener 对象中得到的;
- 通过 acquireNextImage() 方法获取到一个Image对象,然后通过 image.planes[0].buffer 得到 byteBuffer,将这个 byteBuffer 转换成 byteArray ;
- 这个 byteArray 就是拍照所得到的图像数据。然后就可以把这个 byteArray 保存成图片到手机存储中;
8、 释放相机及线程
- fun releaseCamera() {
- mCameraCaptureSession?.close()
- mCameraCaptureSession = null
- mCameraDevice?.close()
- mCameraDevice = null
- mImageReader?.close()
- mImageReader = null
- canExchangeCamera = false
- }
- fun releaseThread() {
- handlerThread.quitSafely()
- }
总结
Camera2 API和旧的Camera API区别很大, 刚开始用可能会很不习惯, 但Camera2有很多优势, 提供了非常多的参数供我们控制;
一起学习加油老铁们;