Camera2动态调整预览分辨率、拍照分辨率
时间: 2023-09-10 18:06:03 浏览: 146
对于Camera2 API,可以使用以下步骤动态地调整预览分辨率和拍照分辨率:
1. 获取CameraManager实例,并使用getCameraIdList()方法获取可用摄像头的ID列表。
2. 通过CameraManager.openCamera()方法打开所需的摄像头。
3. 获取CameraCharacteristics对象,以获取可用的预览分辨率和拍照分辨率列表。
4. 使用CameraDevice.createCaptureSession()方法创建一个CameraCaptureSession对象,以便在其中设置预览和拍照请求。
5. 在CameraCaptureSession.setRepeatingRequest()方法中设置预览请求,并在需要拍照时使用CameraCaptureSession.capture()方法设置拍照请求。
6. 在设置预览和拍照请求时,使用CaptureRequest.Builder对象设置所需的分辨率。
以下是参考代码:
```
// 获取CameraManager实例
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
// 获取可用摄像头ID列表
String[] cameraIds = cameraManager.getCameraIdList();
// 打开所需的摄像头
cameraManager.openCamera(cameraId, stateCallback, null);
// 获取CameraCharacteristics对象
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
// 获取可用的预览分辨率列表
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
Size[] previewSizes = map.getOutputSizes(SurfaceTexture.class);
// 获取可用的拍照分辨率列表
Size[] pictureSizes = map.getOutputSizes(ImageFormat.JPEG);
// 创建CameraCaptureSession对象
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
try {
// 创建预览请求
CaptureRequest.Builder previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
previewRequestBuilder.addTarget(surface);
previewRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CameraMetadata.CONTROL_AE_MODE_ON_AUTO_FLASH);
// 设置预览分辨率
previewRequestBuilder.set(CaptureRequest.SCALER_CROP_REGION, previewSize);
CaptureRequest previewRequest = previewRequestBuilder.build();
// 设置持续的预览请求
session.setRepeatingRequest(previewRequest, null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
Toast.makeText(MainActivity.this, "配置失败", Toast.LENGTH_SHORT).show();
}
}, null);
// 创建拍照请求
CaptureRequest.Builder captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureRequestBuilder.addTarget(imageReader.getSurface());
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CameraMetadata.CONTROL_AE_MODE_ON_AUTO_FLASH);
// 设置拍照分辨率
captureRequestBuilder.set(CaptureRequest.SCALER_CROP_REGION, pictureSize);
CaptureRequest captureRequest = captureRequestBuilder.build();
// 设置单次拍照请求
session.capture(captureRequest, null, null);
```
阅读全文