android java CameraX调用系统相机
时间: 2023-10-12 17:04:35 浏览: 130
CameraX:CameraX演示应用
在 Android 中,使用 CameraX API 调用系统相机可以简化相机的集成和开发过程。以下是步骤:
1. 添加依赖项
在 app 的 build.gradle 文件中添加以下依赖项:
```
dependencies {
def camerax_version = "1.0.0-beta12"
// CameraX core library
implementation "androidx.camera:camera-core:$camerax_version"
// CameraX Camera2 extensions
implementation "androidx.camera:camera-camera2:$camerax_version"
// CameraX Lifecycle library
implementation "androidx.camera:camera-lifecycle:$camerax_version"
// CameraX View class
implementation "androidx.camera:camera-view:1.0.0-alpha24"
}
```
2. 在布局文件中添加相机预览视图
在布局文件中添加一个 CameraView 视图,该视图将用于显示相机预览:
```
<androidx.camera.view.CameraView
android:id="@+id/cameraView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
3. 创建相机实例
在 Activity 或 Fragment 中创建相机实例:
```
private lateinit var camera: Camera
private lateinit var cameraSelector: CameraSelector
private fun startCamera() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener(Runnable {
// Camera provider is now guaranteed to be available
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
// Set up the preview use case
val preview = Preview.Builder().build().also {
it.setSurfaceProvider(cameraView.surfaceProvider)
}
// Set up the image capture use case
val imageCapture = ImageCapture.Builder().build()
// Set up the image analysis use case
val imageAnalyzer = ImageAnalysis.Builder().build().also {
it.setAnalyzer(cameraExecutor, LuminosityAnalyzer())
}
// Select the back camera as a default
cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
// Set up the camera instance
camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture, imageAnalyzer)
}, ContextCompat.getMainExecutor(this))
}
```
4. 启动相机
在 onCreate() 方法中启动相机:
```
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
startCamera()
}
```
5. 拍照
实现拍照功能,可以在按钮点击事件中调用以下代码:
```
private fun takePhoto() {
val imageCapture = imageCapture ?: return
val photoFile = File(
outputDirectory,
SimpleDateFormat(FILENAME_FORMAT, Locale.US).format(System.currentTimeMillis()) + ".jpg"
)
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
imageCapture.takePicture(
outputOptions,
ContextCompat.getMainExecutor(this),
object : ImageCapture.OnImageSavedCallback {
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
val savedUri = Uri.fromFile(photoFile)
val msg = "Photo saved: $savedUri"
Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
}
override fun onError(exception: ImageCaptureException) {
Log.e(TAG, "Photo capture failed: ${exception.message}", exception)
}
}
)
}
```
以上是使用 CameraX API 调用系统相机的步骤。
阅读全文