安卓texture拍照实现存储
时间: 2023-07-13 12:28:35 浏览: 89
在安卓上使用TextureView进行相机预览和拍照,可以通过设置相机回调函数来实现照片存储。以下是实现步骤:
1. 获取相机服务和相机ID
```
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = cameraManager.getCameraIdList()[0]; //获取第一个相机ID
```
2. 打开相机并设置TextureView作为预览显示
```
cameraManager.openCamera(cameraId, new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice camera) {
try {
cameraDevice = camera;
SurfaceTexture texture = textureView.getSurfaceTexture();
texture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight());
Surface surface = new Surface(texture);
captureRequestBuilder = camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
camera.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(CameraCaptureSession session) {
try {
captureSession = session;
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
captureSession.setRepeatingRequest(captureRequestBuilder.build(), null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
...
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
...
}, null);
```
3. 设置拍照回调函数,拍照后保存照片
```
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureRequestBuilder.addTarget(imageReader.getSurface());
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, getJpegOrientation(cameraCharacteristics, deviceOrientation));
CaptureRequest captureRequest = captureRequestBuilder.build();
captureSession.capture(captureRequest, new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(MainActivity.this, "照片已保存", Toast.LENGTH_SHORT).show();
}
}, null);
```
其中,ImageReader是用来读取拍照结果的类,可以通过以下代码创建:
```
ImageReader imageReader = ImageReader.newInstance(imageWidth, imageHeight, ImageFormat.JPEG, 1);
imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = reader.acquireNextImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
save(bytes);
image.close();
}
}, null);
```
save()函数用来保存照片到文件中,你可以自行实现该函数。注意,需要在AndroidManifest.xml文件中添加相机和存储权限。
阅读全文