使用 Camera2调用系统相机
时间: 2023-09-16 18:13:34 浏览: 174
调用系统照相机
使用Camera2 API调用系统相机需要以下步骤:
1.添加权限到 AndroidManifest.xml 文件中:
```xml
<uses-permission android:name="android.permission.CAMERA" />
```
2.在布局文件中添加一个 SurfaceView 用于预览相机图像:
```xml
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
3.在 Activity 中获取 SurfaceView 对象并创建 CameraDevice:
```java
private CameraDevice cameraDevice;
private CaptureRequest.Builder captureRequestBuilder;
private SurfaceView surfaceView;
private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice camera) {
cameraDevice = camera;
createCameraPreview();
}
@Override
public void onDisconnected(CameraDevice camera) {
cameraDevice.close();
}
@Override
public void onError(CameraDevice camera, int error) {
cameraDevice.close();
cameraDevice = null;
}
};
private void openCamera() {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
Size[] outputSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
.getOutputSizes(SurfaceHolder.class);
Size size = outputSizes[0];
manager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
```
4.为 CameraDevice 创建预览会话:
```java
private void createCameraPreview() {
try {
SurfaceHolder holder = surfaceView.getHolder();
holder.setFixedSize(size.getWidth(), size.getHeight());
holder.setKeepScreenOn(true);
final Surface surface = holder.getSurface();
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(CameraCaptureSession session) {
try {
CaptureRequest captureRequest = captureRequestBuilder.build();
session.setRepeatingRequest(captureRequest, null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(CameraCaptureSession session) {
Toast.makeText(MainActivity.this, "Failed to configure camera", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
```
5.在 Activity 的 onResume() 方法中调用 openCamera() 方法:
```java
@Override
protected void onResume() {
super.onResume();
openCamera();
}
```
6.在 Activity 的 onPause() 方法中释放相机资源:
```java
@Override
protected void onPause() {
super.onPause();
if (cameraDevice != null) {
cameraDevice.close();
cameraDevice = null;
}
}
```
阅读全文