Camera2拍照kotlin
时间: 2024-08-13 09:06:51 浏览: 110
Camera2 API 是Android 6.0 (API level 23) 引入的一个用于拍照和录像的强大工具,它提供了更灵活、高效和低级别的控制,相比之前的Camera API。在 Kotlin 中使用 Camera2,你可以更好地控制相机的各种设置和流。
以下是使用 Camera2 在 Kotlin 中进行拍照的基本步骤:
1. **初始化CameraManager**:
```kotlin
val cameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
```
2. **获取相机列表**:
```kotlin
val cameraIds = cameraManager.cameraIdList
```
3. **请求权限**:
```kotlin
val permissions = arrayOf(Manifest.permission.CAMERA)
if (!ContextCompat.checkSelfPermission(this, permissions) == PackageManager.PERMISSION_GRANTED) {
// 请求权限
}
```
4. **打开相机并选择后置或前置摄像头**:
```kotlin
val cameraId = cameraIds.firstOrNull { cameraManager.isCameraPresent(it) } ?: throw RuntimeException("No camera found")
val camera = cameraManager.openCamera(cameraId, CameraDevice.StateCallback(), null)
```
5. **创建CaptureSession并配置相机参数**:
```kotlin
val surfaceHolder: SurfaceHolder = ... // 获取SurfaceView的SurfaceHolder
val previewRequestBuilder = camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
previewRequestBuilder.addTarget(surfaceHolder.surface)
camera.createCaptureSession(List.of(surfaceHolder), object : CameraCaptureSession.StateCallback() {
...
}, null)
```
6. **启动预览并准备拍照**:
```kotlin
cameraManager.createCameraCaptureSession(cameraId, object : CameraCaptureSession.StateCallback() {
override fun onConfigured(session: CameraCaptureSession) {
val preview = session.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
session.setRepeatingRequest(preview, null, null)
// 添加拍照请求
val photoRequestBuilder = session.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE)
photoRequestBuilder.addTarget(surfaceHolder.surface)
takePicture(session, photoRequestBuilder)
}
}, null)
```
7. **处理拍照请求**:
```kotlin
private fun takePicture(session: CameraCaptureSession, photoRequestBuilder: CaptureRequest.Builder) {
photoRequestBuilder.addTarget(surfaceHolder.surface)
session.capture(photoRequestBuilder.build(), object : CaptureCallback() {
@Throws(InterruptedException::class)
override fun onCaptureCompleted(captureSession: CameraCaptureSession, request: CaptureRequest, result: TotalCaptureResult) {
// 处理图片,关闭相机等
}
}, null)
}
```
8. **释放资源**:
```kotlin
session.close()
camera.close()
```
阅读全文