OpenHarmony3.2 beta4上照相机的使用之1--开启照相机预览画面

随着OpenHarmony的版本更新,在3.2上已经提供了非常丰富的API来调用照相机。此处讲解的是原生的使用相机的流程,并发像Android普通应用开发一样通过一个intent直接调用系统相机应用进行拍照,根据原生的调用相机的API可以让大家自己定义功能更加丰富的相机应用。

这里为何我特意强调是OpenHarmony3.2 beta4,因为我发现即使同为3.2版本,beta4上的Camera相关的api和beta2版本差距都非常大,于是选取了当前最新的版本进行讲解。

既然使用相机,那么第一步是先想办法把相机点亮,即能通过摄像头看到预览画面,后面才是拍照、录像、分布式拍照等功能实现。

关于sdk的问题

目前在OpenHarmony3.2上调用相机,需要使用ohos-full-sdk,而非大家下载DevEco Studio所带的sdk,那个sdk被称作为public sdk。关于sdk的替换办法可以参考官方文档“ full-SDK替换指南”,我这里不过多赘述。

此处核心要注意的一点是,目前我3.2 beta4上用的sdk对应的版本号为3.2.9.4

而目前官方文档上写的能下载到的sdk最高版本只有3.2.5.6。

因此,需要我们手动下载系统源码,自己完成sdk的编译才行,我这里是基于3.2 beta4的系统源码自行编译出来的full-sdk。

启用相机打开预览画面核心流程与代码实现

(1)动态权限申请

需要获取ohos.permission.CAMERA权限

(2)相机相关API操作流程

上面是相机完整功能使用的时序图,这里我们先只按照时序图中的流程只实现预览部分。

(3)配合XComponent组件完成相机预览流的输出

XComponent组件中通过XComponentController的getXComponentSurfaceId方法可以获取到sufaceId,然后通过相机管理对象cameraManager.createPreviewOutput这个关键方法可以绑定该surface,从而实现预览画面的输出。

启用相机打开预览画面代码实现

import camera from '@ohos.multimedia.camera'

const PERMISSIONS: Array<string> = [
  'ohos.permission.CAMERA']
let previewWidth;
let previewHeight;
@Entry
@Component
struct Index {
  private mXComponentController: XComponentController = new XComponentController()
  private surfaceId: string = '-1'

  async initCamera(surfaceId: string){
    //动态获取隐私权限
    let context = getContext(this) as any
    await context.requestPermissionsFromUser(PERMISSIONS)
    console.log('grantPermission,requestPermissionsFromUser');
    // 创建CameraManager对象
    let cameraManager = await camera.getCameraManager(context)
    if (!cameraManager) {
      console.error('Failed to get the CameraManager instance');
    }
    // 获取相机列表
    let cameraArray = await cameraManager.getSupportedCameras()
    if (!cameraArray) {
      console.error('Failed to get the cameras');
    }
    for (let index = 0; index < cameraArray.length; index++) {
      console.log('cameraId : ' + cameraArray[index].cameraId)                          // 获取相机ID
      console.log('cameraPosition : ' + cameraArray[index].cameraPosition)              // 获取相机位置
      console.log('cameraType : ' + cameraArray[index].cameraType)                      // 获取相机类型
      console.log('connectionType : ' + cameraArray[index].connectionType)              // 获取相机连接类型
    }

    // 创建相机输入流
    let cameraInput = await cameraManager.createCameraInput(cameraArray[0])

    //  打开相机
    await cameraInput.open().then(() => {
      console.log('opencamera succ.');
    }).catch(function(err){
      console.log("opencamera failed with error:"+ err);
    });

    // 获取相机设备支持的输出流能力
    let cameraOutputCap = await cameraManager.getSupportedOutputCapability(cameraArray[0]);
    if (!cameraOutputCap) {
      console.error("outputCapability outputCapability == null || undefined")
    } else {
      console.log("outputCapability: " + JSON.stringify(cameraOutputCap));
    }

    //获取相机支持的输出能力--支持的预览配置信息
    let previewProfilesArray = cameraOutputCap.previewProfiles;
    if (!previewProfilesArray) {
      console.error("createOutput previewProfilesArray == null || undefined")
    }else{
      console.log("previewProfiles:"+JSON.stringify(previewProfilesArray[0]))
      previewWidth = previewProfilesArray[0].size.width;
      previewHeight = previewProfilesArray[0].size.height;
    }

    // 创建预览输出流,其中参数 surfaceId 参考下面 XComponent 组件,预览流为XComponent组件提供的surface
    let previewOutput = await cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId)
    if (!previewOutput) {
      console.error("Failed to create the PreviewOutput instance.")
    }else{
      console.log("create the PreviewOutput instance succ.")
    }

    //创建会话
    let captureSession = await cameraManager.createCaptureSession()
    if (!captureSession) {
      console.error('Failed to create the CaptureSession instance.');
      return;
    }
    console.log('Callback returned with the CaptureSession instance.' + captureSession);

    // 开始配置会话
    await captureSession.beginConfig().then(()=>{
      console.log('captureSession beginConfig succ');
    }).catch(function(err){
      console.log("captureSession beginConfig failed with error:"+ err);
    });
 
    // 向会话中添加相机输入流
    await captureSession.addInput(cameraInput).then(() => {
      console.log('captureSession addInput instance is added.');
    }).catch(function(err){
      console.log("captureSession addInput failed with error:"+ err);
    });

    // 向会话中添加预览输入流
    await captureSession.addOutput(previewOutput).then(() => {
      console.log('captureSession addOutput previewOutput instance is added.');
    }).catch(function(err){
      console.log("captureSession addOutput previewOutput failed with error:"+ err);
    });

    // 提交会话配置
    await captureSession.commitConfig().then(() => {
      console.log('captureSession commitConfig success.');
    }).catch(function(err){
      console.log("captureSession commitConfig failed with error:"+ err);
    });
    // 启动会话
    await captureSession.start().then(() => {
      console.log('captureSession start success.');
    }).catch(function(err){
      console.log("captureSession start failed with error:"+ err);
    });
  }

  build() {
    Flex() {
      XComponent({                                                                     // 创建XComponent
        id: '',
        type: 'surface',
        libraryname: '',
        controller: this.mXComponentController
      })
        .onLoad(() => {                                                                  // 设置onload回调
          // 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置
          this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:previewWidth,surfaceHeight:previewHeight})
          // 获取Surface ID
          this.surfaceId = this.mXComponentController.getXComponentSurfaceId()
          this.initCamera(this.surfaceId)
        })
        .width('100%')                                                                 // 设置XComponent宽度
        .height('100%')                                                                // 设置XComponent高度
    }
  }

}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值