Android Camera2入门

Android Camera2入门系列1 – Camera2在textureView预览
Android Camera2入门系列2 – ImageReader取得预览数据
Android Camera2入门系列3 – Image中取得YUV数据及YUV格式了解
Android Camera2入门系列4 – libyuv的编译和运用

本文供给最easy的Camera2的入门,供入门查看,意在精简,深化内容看后续文章。

The android.hardware.camera2 package provides an interface to individual camera devices connected to an Android device. It replaces the deprecated[Camera]class. camera2给Android的给个Camera设备供给了接口,并且deprecated掉了Camera类

下面是翻译了部分Camera2的API描述:基本上涉及了咱们运用camera2的一切的API:
经过CameraManager能查询本设备有多少个available的Camera设备。
每个CameraDevice设备供给了一系列静态参数去描述当时的Camera设备,比方设置或许输出参数,这些参数经过[CameraCharacteristics]供给出来,经过[getCameraCharacteristics(cameraId)]获取。

从相机设备获取一个或许多个image,首要有必要创立一个CameraCaptureSession并输出到一个或多个方针Surface上。每个Surface有必要预先设置适宜的预览尺度,这个尺度有必要是Camera支撑的尺度。方针Surface能够被一系列的类所持有,比方SurfaceView,SurfaceTexture,MediaCodec,MediaRecorder,AllocationImageReader也便是说Camera的输出能够被分发到多个Surface上面。

通常,相机预览图画能够被发送到SurfaceView或许TextureView上面,像摄影的时候去单独获取某一帧或许特效相机类的App取得要处理的RAW数据流能够经过ImageReader来获取JPEG格式或许YUV格式的图画数据。比方要用RenderScript, OpenGL ES或许直接在native处理的数据就引荐运用YUV_420_888数据格式来承载。
假如相机设备要获取Image(也便是获取图画的raw数据:JPEG或许YUV数据),咱们需求创立一个界说了相机需求的参数的CaptureRequestCameraDevice有工厂办法去创立一个request builder。 一旦request被创立出来,它能够被一个active状况的session拿去得到一个Image(one-shot)或许多个Image(endless),也便是说session经过request去得到一张图或许多张图。

//得到一个Image
session.capture(request, null, mCameraHandler);
//一向回调回来Image
session.setRepeatingRequest(request, null, mCameraHandler);

API运用流程大体如下:

  1. 经过context.getSystemService(Context.CAMERA_SERVICE) 获取CameraManager.
  2. 调用CameraManager .open()办法在回调中得到CameraDevice.
  3. 经过CameraDevice.createCaptureSession() 在回调中获取CameraCaptureSession.
  4. 构建CaptureRequest, 有三种形式可选 预览/摄影/录像.
  5. 经过 CameraCaptureSession发送CaptureRequest, capture表明只发一次恳求, setRepeatingRequest表明不断发送恳求.
  6. 摄影数据能够在ImageReader.OnImageAvailableListener回调中获取, CaptureCallback中则可获取摄影实践的参数和Camera当时状况.

Android Camera2入门系列1 - Camera2在textureView预览

上文提到了Camera2的某些必要的API。其实单纯的去看某个类或某些类的责任,只是看这些API的功能描述只会看的头大,由于camera2确实供给了许多API来操控。还不如直接来看一个demo来的愈加直观,引荐咱们不要复制,哪怕看着自己敲一遍,形象会深入许多。

public class Camera2Provider {
    private Activity mContext;
    private String mCameraId;
    private Handler mCameraHandler;
    private CameraDevice mCameraDevice;
    private TextureView mTextureView;
    private CaptureRequest.Builder mPreviewBuilder;
    private Size previewSize;
    public Camera2Provider(Activity mContext) {
        this.mContext = mContext;
        //创立了一个Thread来供Camera运行运用,运用HandlerThread而不运用Thread是由于HandlerThread给咱们创立了Looper,不必咱们自己创立了。
        HandlerThread handlerThread = new HandlerThread("camera");
        handlerThread.start();
        mCameraHandler = new Handler(handlerThread.getLooper());
    }
    /**
     * 设置预览view
     *
     * @param textureView 需求预览的TextureView
     */
    public void initTexture(TextureView textureView) {
        mTextureView = textureView;
        textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                openCamera(width, height);
            }
            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {}
            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {return false;}
            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {}
        });
    }
    /**
     * surface ready的时候敞开Camera
     *
     * @param width  surface的宽
     * @param height surface的高
     */
    private void openCamera(int width, int height) {
        CameraManager cameraManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
        try {
            for (String cameraId : cameraManager.getCameraIdList()) {
                //描述相机设备的属性类
                CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
                //获取是前置还是后置摄像头
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                //运用后置摄像头
                if (facing != null && facing == CameraCharacteristics.LENS_FACING_BACK) {
                    StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                    if (map != null) {
                        previewSize = CameraUtil.getOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height);
                        mCameraId = cameraId;
                    }
                }
            }
            String[] params = new String[]{Manifest.permission.CAMERA};
            if (!PermissionUtil.checkPermission(mContext, params)) {
                PermissionUtil.requestPermission(mContext, "", 0, params);
            }
            cameraManager.openCamera(mCameraId, mStateCallback, mCameraHandler);
        } catch (CameraAccessException r) {}
    }
    /**
     * 状况回调
     */
    private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(CameraDevice camera) {
            mCameraDevice = camera;
            SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
            surfaceTexture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight());
            Surface previewSurface = new Surface(surfaceTexture);
            try {
                mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
                //假如需求多个surface能够add多个
                mPreviewBuilder.addTarget(previewSurface);
                mCameraDevice.createCaptureSession(Arrays.asList(previewSurface), mStateCallBack, mCameraHandler);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onDisconnected(CameraDevice camera) {
            camera.close();
        }
        @Override
        public void onError(CameraDevice camera, int error) {
            camera.close();
        }
    };
    private CameraCaptureSession.StateCallback mStateCallBack = new CameraCaptureSession.StateCallback() {
        @Override
        public void onConfigured(CameraCaptureSession session) {
            CaptureRequest request = mPreviewBuilder.build();
            try {
                //获取一个Image,one-shot
//                session.capture(request, null, mCameraHandler);
                //敞开获取Image,repeat形式
                session.setRepeatingRequest(request, null, mCameraHandler);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onConfigureFailed(CameraCaptureSession session) {}
    };
    /**
     * 记住关掉Camera
     */
    public void closeCamera() {
        mCameraDevice.close();
    }
}

需求留意的几个问题:

  1. 记住增加权限,并自己完成动态恳求权限。
  2. 创立一个Thread供Camera2运用。
  3. 留意预览尺度和Camera能供给的尺度。

github代码:Camera2Provider.java 欢迎star/follow

接着看下一篇怎么获取回调的数据Android Camera系列2 – ImageReader取得预览数据