使用CameraX时,ImageAnalysis默认编码格式为ImageFormat.YUV_420_888,此时同时添加ImageCapture,若ImageCapture编码格式也设置为ImageFormat.YUV_420_888格式,会导致崩溃,报如下错误:
java.lang.IllegalArgumentException: No supported surface combination is found for camera device - Id : 0. May be attempting to bind too many use cases.
ImageCapture默认编码格式为ImageFormat.JPEG,保持默认格式即可。
原因未知,猜测可能编码冲突
// Set up the capture use case to allow users to take photos
val imageCapture = ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
.setBufferFormat(ImageFormat.YUV_420_888)//有ImageAnalysis 时不能使用ImageFormat.YUV_420_888格式,可能抢占同编码一通道 会崩溃
.setTargetResolution(Size(1280, 720)).build()
// Attach use cases to the camera with the same lifecycle owner
var imageAnalysis: ImageAnalysis? = null
frameListener?.let { frameListener ->
imageAnalysis = ImageAnalysis.Builder()
.setTargetResolution(Size(1280, 720))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build().apply { setAnalyzer(mCameraExecutor, frameListener) }
}
附完整示例:
package com.gcsdk.cameraxutils
import androidx.camera.lifecycle.ProcessCameraProvider
import kotlin.jvm.JvmOverloads
import androidx.camera.view.PreviewView
import com.gcsdk.cameraxutils.CameraXUtils
import androidx.core.content.ContextCompat
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.ImageFormat
import android.util.Log
import android.util.Size
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.*
import androidx.camera.core.ImageCapture.O