Camera2 相机怎么预览
时间: 2023-11-26 10:02:39 浏览: 82
使用 Camera2 API 进行相机预览需要以下步骤:
1. 获取相机服务。
```java
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
```
2. 获取相机 ID。
```java
String cameraId = cameraManager.getCameraIdList()[0];
```
3. 打开相机。
```java
cameraManager.openCamera(cameraId, new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice camera) {
mCameraDevice = camera;
}
@Override
public void onDisconnected(CameraDevice camera) {
camera.close();
mCameraDevice = null;
}
@Override
public void onError(CameraDevice camera, int error) {
camera.close();
mCameraDevice = null;
}
}, null);
```
4. 创建预览请求。
```java
private void createPreviewSession() {
try {
SurfaceTexture texture = mTextureView.getSurfaceTexture();
texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
Surface surface = new Surface(texture);
mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(surface);
mCameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(CameraCaptureSession session) {
mCaptureSession = session;
try {
mPreviewRequest = mPreviewRequestBuilder.build();
mCaptureSession.setRepeatingRequest(mPreviewRequest, null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(CameraCaptureSession session) {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
```
5. 开始预览。
```java
private void startPreview() {
try {
createPreviewSession();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
```
注意:以上代码仅供参考,具体实现可能需要根据实际需求进行修改。
阅读全文