TakePicturePreview示例
时间: 2024-05-17 20:19:44 浏览: 83
以下是一个使用 Camera2 API 实现 TakePicturePreview 功能的示例代码:
1. 在布局文件中添加一个 TextureView 控件用于显示相机预览:
```xml
<TextureView
android:id="@+id/texture_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 在 Activity 中初始化 Camera2 API:
```java
private CameraManager mCameraManager;
private String mCameraId;
private CameraDevice mCameraDevice;
private CaptureRequest.Builder mPreviewRequestBuilder;
private CameraCaptureSession mCaptureSession;
private Size mPreviewSize;
private ImageReader mImageReader;
private void initCamera() {
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
// 获取可用的摄像头列表
String[] cameraIds = mCameraManager.getCameraIdList();
for (String cameraId : cameraIds) {
// 获取摄像头的特性
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId);
// 判断是否为后置摄像头
if (characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) {
mCameraId = cameraId;
break;
}
}
// 打开相机
mCameraManager.openCamera(mCameraId, mCameraStateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
```
3. 在 CameraDevice.StateCallback 中获取相机预览尺寸并设置预览界面:
```java
private CameraDevice.StateCallback mCameraStateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice camera) {
mCameraDevice = camera;
try {
// 获取相机预览尺寸
StreamConfigurationMap map = mCameraManager.getCameraCharacteristics(mCameraId)
.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
mPreviewSize = getOptimalPreviewSize(map.getOutputSizes(SurfaceTexture.class), mTextureView.getWidth(), mTextureView.getHeight());
// 设置预览界面
SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
Surface previewSurface = new Surface(surfaceTexture);
mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(previewSurface);
// 创建 ImageReader 用于拍照
mImageReader = ImageReader.newInstance(mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.JPEG, 1);
mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, null);
// 打开相机预览
mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, mImageReader.getSurface()), mSessionStateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onDisconnected(@NonNull CameraDevice camera) {
camera.close();
mCameraDevice = null;
}
@Override
public void onError(@NonNull CameraDevice camera, int error) {
camera.close();
mCameraDevice = null;
}
};
private Size getOptimalPreviewSize(Size[] sizes, int width, int height) {
List<Size> sizeList = new ArrayList<>();
for (Size size : sizes) {
if (size.getWidth() <= width && size.getHeight() <= height) {
sizeList.add(size);
}
}
if (sizeList.isEmpty()) {
return sizes[0];
}
Size[] sizeArray = new Size[sizeList.size()];
sizeList.toArray(sizeArray);
return Collections.max(Arrays.asList(sizeArray), new CompareSizesByArea());
}
```
4. 在 CameraCaptureSession.StateCallback 中启动相机预览:
```java
private CameraCaptureSession.StateCallback mSessionStateCallback = new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
mCaptureSession = session;
try {
// 自动对焦
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
// 打开闪光灯
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
// 设置预览帧率
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, new Range<Integer>(30, 30));
// 开始预览
mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
}
};
```
5. 在 ImageReader.OnImageAvailableListener 中保存拍照图片并显示预览:
```java
private ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
try {
// 保存拍照图片
Image image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
File pictureFile = new File(getExternalFilesDir(null), "picture.jpg");
FileOutputStream outputStream = new FileOutputStream(pictureFile);
outputStream.write(data);
outputStream.close();
// 显示预览
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
mTextureView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
};
```
在用户拍照后,可以在相应的按钮点击事件中调用 mCaptureSession.capture 方法拍照并保存图片。在保存图片之后,需要使用 startActivityForResult 方法启动另一个 Activity,并将图片路径返回给调用方。
阅读全文