android camera2 分辨率代码如何写
时间: 2023-08-06 11:10:04 浏览: 113
下面是一个通过 Camera2 API 实现设置预览分辨率的示例代码:
```java
// 获取 CameraCharacteristics
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
// 获取支持的预览尺寸列表
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
Size[] previewSizes = map.getOutputSizes(SurfaceTexture.class);
// 选择一个预览尺寸
Size previewSize = chooseOptimalSize(previewSizes, desiredWidth, desiredHeight);
// 创建预览请求
CaptureRequest.Builder builder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
builder.addTarget(surface);
// 设置预览尺寸
builder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, new Range<Integer>(30, 30));
builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
builder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_AUTO);
builder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
builder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
builder.set(CaptureRequest.SCALER_CROP_REGION, cropRegion);
builder.set(CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION, 0);
builder.set(CaptureRequest.CONTROL_AE_LOCK, false);
builder.set(CaptureRequest.CONTROL_AWB_LOCK, false);
builder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_IDLE);
builder.set(CaptureRequest.JPEG_ORIENTATION, getJpegOrientation(characteristics, sensorOrientation));
// 启动预览
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(CameraCaptureSession session) {
try {
session.setRepeatingRequest(builder.build(), null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(CameraCaptureSession session) {
Log.e(TAG, "Failed to configure camera preview session");
}
}, null);
```
其中,`chooseOptimalSize` 方法可以根据设备支持的预览尺寸列表和期望的宽高,选择一个最适合的预览尺寸。
```java
private Size chooseOptimalSize(Size[] choices, int width, int height) {
List<Size> bigEnough = new ArrayList<>();
for (Size option : choices) {
if (option.getWidth() >= width && option.getHeight() >= height) {
bigEnough.add(option);
}
}
if (bigEnough.size() > 0) {
return Collections.min(bigEnough, new CompareSizesByArea());
} else {
return choices[0];
}
}
private static class CompareSizesByArea implements Comparator<Size> {
@Override
public int compare(Size lhs, Size rhs) {
// 强转为 long 避免乘法溢出
return Long.signum((long) lhs.getWidth() * lhs.getHeight() - (long) rhs.getWidth() * rhs.getHeight());
}
}
```
阅读全文