以前用的是Camera,但是现在Camera已经被官方弃用了,所以这里使用的是Camera2进行演示
使用Camera需要注意的就是权限的获取,必须有权限
Camera2跟Camera1不一样,它使用了很多个类,每个类有自己的功能
这几个类是主要使用的,其他的比如 CameraCharacteristics 类用于获取跟摄像头有关的信息等等
1、CameraManager获取系统摄像头
1 CameraManager cameraManager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
2、CameraManager打开指定摄像头,让Device进行操作
String cameraId = "" + CameraCharacteristics.LENS_FACING_FRONT;//得到后摄像头编号
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION\_GRANTED) {
return;
}
CameraDevice.StateCallback deviceCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice camera) {
cameraDevice = camera;
}
@Override
public void onDisconnected(@NonNull CameraDevice camera) {
}
@Override
public void onError(@NonNull CameraDevice camera, int error) {
Log.e(TAG,"cameraManager打开摄像头失败");
}
};
try {
cameraManager.openCamera(cameraId, deviceCallback, null);
} catch (CameraAccessException e) {
Log.e(TAG,"cameraManager访问摄像头失败");
}
3、使用CaptureRequest.Builder 指定配置信息和画面图片的传递
CaptureRequest.Builder previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
//将预览数据传递
previewRequestBuilder.addTarget(imageReader.getSurface());
previewRequestBuilder.addTarget(surfaceHolder.getSurface());
// 自动对焦
previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
// 打开闪光灯
previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
4、Device创建Session进行预览
cameraDevice.createCaptureSession(Arrays.asList(surfaceHolder.getSurface(), imageReader.getSurface()), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
cameraCaptureSession = session;
CaptureRequest captureRequest = previewRequestBuilder.build();
try {
cameraCaptureSession.setRepeatingRequest(captureRequest,captureCallback,cameraHandler);
} catch (CameraAccessException e) {
Log.e(TAG,"cameraCaptureSession访问摄像头失败");
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
}
},null);
在参数中的surfaceHolder是当前画面的SurfaceView,imageReader是在下面进行定义的
5、使用imageReader对预览的图片进行操作
final int MAX_PREVIEW_WIDTH = 1920;
final int MAX_PREVIEW_HEIGHT = 1080;
//imageReader通过将得到的图片存放在队列中,再取出来进行操作
//队列满了就不再放入新的图片,设置图片队列大小为10
imageReader = ImageReader.newInstance(MAX\_PREVIEW\_WIDTH,MAX\_PREVIEW\_HEIGHT, ImageFormat.JPEG,10);
imageReader.setOnImageAvailableListener(reader -> {
//取出最新的图片并清除队列里的旧图片
Image image = reader.acquireLatestImage();
//todo 对获取的图片进行操作
//将图片转换成Bitmap
ByteBuffer buffer = image.getPlanes()\[0\].getBuffer();
byte\[\] bytes = new byte\[buffer.remaining()\];
buffer.get(bytes);//由缓冲区存入字节数组
final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//释放资源
image.close();
},cameraHandler);//由handler去执行这里面的代码
手机扫一扫
移动阅读更方便
你可能感兴趣的文章