Hongmeng Application Development Media (Camera)

I. Overview

HarmonyOSThe camera module supports the development of camera services. Developers can implement camera hardware access, operation, and development of new functions through open interfaces. The most common operations include previewing, taking pictures, continuous shooting, and recording.

1. Basic concepts

  • Camera static capability

    A series of parameters used to describe the inherent capabilities of the camera, such as orientation, supported resolutions and other information.

  • Physical camera

    A physical camera is an independent physical camera device. The physical camera IDis a unique string used to identify each physical camera.

  • Logical camera

    A logical camera is an abstract device composed of multiple physical cameras. The logical camera completes certain functions of the camera, such as large aperture, zoom, etc., by controlling multiple physical camera devices at the same time. A logical camera IDis a unique string that identifies the abstract capabilities of multiple physical cameras.

  • Frame capture

    The capture of frames after the camera is started is collectively called frame capture. It mainly includes single frame capture, multi-frame capture, and loop frame capture.

  • Single frame capture

    It refers to the capture of a frame of data in the frame data stream after the camera is started, which is often used for ordinary photography.

  • Multi-frame capture

    It refers to the continuous capture of multiple frames of data in the frame data stream after the camera is started, which is often used for continuous shooting.

  • Loop frame capture

    It means that after the camera is started, the frame data is always captured in the frame data stream, which is often used for previewing and recording.

2. Restrictions and limitations

  • Only one camera application can be running at the same time.
  • There is state control inside the camera module, and the developer must call the interfaces in order according to the process in the guide document, otherwise problems such as call failure may occur.
  • In order to develop camera applications with better compatibility, please make sure to check the capabilities before creating camera objects or parameter-related settings.

3. Development process

img

2. Some instructions and necessary steps before development

1. Three important interfaces

Package names Features
ohos.media.camera.CameraKit Camera function entry class. Get the list of currently supported cameras and their static capability information, and create a camera object.
ohos.media.camera.device Camera equipment operation class. Provides functions such as camera capability query, camera configuration, camera frame capture, and camera status callback.
ohos.media.camera.params Camera parameter class. Provide definitions of camera attributes, parameters and operation results.

2. Permission application

The camera involves the following four permissions

Authority name Permission attribute value Is it mandatory
Camera permissions ohos.permission.CAMERA required
Recording permission ohos.permission.MICROPHONE Optional (apply when recording is required)
Storage permissions ohos.permission.WRITE_USER_STORAGE Optional (apply when you need to save images and videos to the external storage of the device)
Location permissions ohos.permission.LOCATION Optional (apply when you need to save the image and video location information)

Declare the permissions in the configuration file. The diagram here is convenient. I have requested all the above four permissions, so I do Demon’t need to add them one by one.

"reqPermissions": [
  {
    
    
    "name": "ohos.permission.CAMERA",
    "name": "ohos.permission.MICROPHONE",
    "name": "ohos.permission.LOCATION",
    "name": "ohos.permission.WRITE_USER_STORAGE"
  }

image-20210120141535344

Request permission in MainAbilitythe OnStartmethod

public class MainAbility extends Ability {
    
    
    @Override
    public void onStart(Intent intent) {
    
    
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        String[] permissions = {
    
    "ohos.permission.CAMERA"
                , "ohos.permission.MICROPHONE"
                , "ohos.permission.LOCATION"
                , "ohos.permission.WRITE_USER_STORAGE"};
        requestPermissionsFromUser(permissions, 0);
    }
}

image-20210120142147059

Third, the creation of camera equipment

CameraKitThe class is the entry class of the camera API, which is used to obtain the characteristics of the camera device and open the camera. Its interface is as follows.

Interface name description
createCamera(String cameraId, CameraStateCallback callback, EventHandler handler) Create camera objects.
getCameraAbility(String cameraId) Get the static capabilities of the specified logical camera or physical camera.
getCameraIds() Get the current logical camera list.
getCameraInfo(String cameraId) Get the information of the specified logical camera.
getInstance(Context context) Get an instance of CameraKit.
registerCameraDeviceCallback(CameraDeviceCallback callback, EventHandler handler) Register the camera usage status callback.
unregisterCameraDeviceCallback(CameraDeviceCallback callback) Log out the camera usage status callback.

Based on the HarmonyOSrealization of a camera application, no matter which device or devices you want to apply to in the future, you must first create an independent camera device before you can continue other camera operations.

Process

public class MainAbilitySlice extends AbilitySlice {
    
    
    private static HiLogLabel hiLogLabel = new HiLogLabel(3, 1, "MainAbility");
    private EventHandler eventHandler = new EventHandler(EventRunner.create("CameraCb"));
    private CameraStateCallback cameraStateCallback = new CameraStateCallback() {
    
    
        @Override
        public void onCreated(Camera camera) {
    
    
            super.onCreated(camera);
            HiLog.info(hiLogLabel, "创建相机设备");
        }

        @Override
        public void onCreateFailed(String cameraId, int errorCode) {
    
    
            super.onCreateFailed(cameraId, errorCode);
            HiLog.info(hiLogLabel, "创建相机设备失败,cameraId = " + cameraId + ",errorCode = " + errorCode);
        }

        @Override
        public void onConfigured(Camera camera) {
    
    
            super.onConfigured(camera);
            HiLog.info(hiLogLabel, "配置相机设备");
        }

        @Override
        public void onPartialConfigured(Camera camera) {
    
    
            super.onPartialConfigured(camera);
            HiLog.info(hiLogLabel, "使用了addDeferredSurfaceSize配置了相机");

        }

        @Override
        public void onConfigureFailed(Camera camera, int errorCode) {
    
    
            super.onConfigureFailed(camera, errorCode);
            HiLog.info(hiLogLabel, "配置相机设备失败");

        }

        @Override
        public void onReleased(Camera camera) {
    
    
            super.onReleased(camera);
            HiLog.info(hiLogLabel, "释放相机设备");

        }

        @Override
        public void onFatalError(Camera camera, int errorCode) {
    
    
            super.onFatalError(camera, errorCode);
            HiLog.info(hiLogLabel, "onFatalError错误");
        }

        @Override
        public void onCaptureRun(Camera camera) {
    
    
            super.onCaptureRun(camera);
            HiLog.info(hiLogLabel, "onCaptureRun错误");
        }

        @Override
        public void onCaptureIdle(Camera camera) {
    
    
            super.onCaptureIdle(camera);
            HiLog.info(hiLogLabel, "onCaptureIdle错误");
        }
    };
    private Button mBtn1;

    @Override
    public void onStart(Intent intent) {
    
    
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        String[] permissions = {
    
    "ohos.permission.CAMERA"
                , "ohos.permission.MICROPHONE"
                , "ohos.permission.LOCATION"
                , "ohos.permission.WRITE_USER_STORAGE"};
        requestPermissionsFromUser(permissions, 0);
        mBtn1 = (Button) findComponentById(ResourceTable.Id_btn1);
        mBtn1.setClickedListener(component -> {
    
    
            createCamera();
        });
    }

    /**
     * @description 测试创建相机设备
     * @author PengHuAnZhi
     * @date 2021/1/20 14:28
     */
    private void createCamera() {
    
    
        /*获取唯一的CameraKit对象是创建新的相机应用的第一步操作*/
        CameraKit cameraKit = CameraKit.getInstance(this.getContext());
        /*如果此步骤操作失败,相机可能被占用或无法使用。如果被占用,必须等到相机释放后才能重新获取CameraKit对象*/
        if (cameraKit != null) {
    
    
            try {
    
    
                String[] cameraIds = cameraKit.getCameraIds();
                if (cameraIds.length <= 0) {
    
    
                    HiLog.info(hiLogLabel, "设备无可用相机设备!");
                } else {
    
    
                    //遍历设备有可以用的相机设备
                    for (String id : cameraIds) {
    
    
                        //相机硬件信息
                        CameraInfo cameraInfo = cameraKit.getCameraInfo(id);
                        //获取相机朝向信息
                        int facingType = cameraInfo.getFacingType();
                        //获取逻辑相机ID。
                        String logicalId = cameraInfo.getLogicalId();
                        List<String> physicalIdList = cameraInfo.getPhysicalIdList();
                        HiLog.info(hiLogLabel, "id = " + id + ",朝向信息为" + facingType + ",逻辑相机id = " + logicalId);
                        HiLog.info(hiLogLabel, "对应的物理相机id列表如下");
                        for (String str : physicalIdList) {
    
    
                            //获取物理相机连接方式
                            int deviceLinkType = cameraInfo.getDeviceLinkType(str);
                            HiLog.info(hiLogLabel, "物理相机id = " + str + ",连接方式 = " + deviceLinkType);
                        }
                        //相机能力信息(比如支持的分辨率列表等)。
                        CameraAbility cameraAbility = cameraKit.getCameraAbility(id);
                        /*CameraAbility类下的API更多,需要就上官方文档查吧,这里只示范一个*/
                        //获取当前相机支持的闪光灯取值范围
                        int[] supportedFlashMode = cameraAbility.getSupportedFlashMode();
                        HiLog.info(hiLogLabel, "闪光灯取值范围为 = " + Arrays.toString(supportedFlashMode));
                        HiLog.info(hiLogLabel, "---------------------------------");
                    }
                    if (cameraStateCallback == null) {
    
    
                        HiLog.info(hiLogLabel, "cameraStateCallback为Null!");
                    }
                    if (eventHandler == null) {
    
    
                        HiLog.info(hiLogLabel, "eventHandler为Null!");
                    }
                    /*第一个参数cameraId可以是上一步获取的逻辑相机列表中的任何一个相机ID。第二和第三个参数负责相机创建和相机运行时的数据和状态检测,务必保证在整个相机运行周期内有效。*/
                    cameraKit.createCamera(cameraIds[0], cameraStateCallback, eventHandler);
                }
            } catch (Exception e) {
    
    
                HiLog.info(hiLogLabel, "获取设备支持的逻辑相机列表错误");
            }
        } else {
    
    
            HiLog.info(hiLogLabel, "获取CameraKit失败了");
        }
    }

    @Override
    public void onActive() {
    
    
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
    
    
        super.onForeground(intent);
    }
}

Test Results

image-20210120160516119

failure? ?

After adjusting for more than an hour, it still doesn't work, and there is no reference material. How can Hongmeng learn? ? ? ? ? ? ?

Stay for more, stop learning.

Guess you like

Origin blog.csdn.net/qq_43509535/article/details/112887256