OpenHarmony上实现分布式相机

最近陆续看到各社区上有关 openharmony 媒体相机的使用开发文档,相机对于富设备来说必不可少,日常中我们经常使用相机完成拍照、人脸验证等。
openharmony 系统一个重要的能力就是分布式,对于分布式相机我也倍感兴趣,之前看到官方对分布式相机的一些说明,这里简单介绍下。
有兴趣可以查看官方文档:分布式相机部件
https://gitee.com/openharmony/distributedhardware_distributed_camera   
分布式框架图
分布式相机框架(distributed hardware)分为主控端和被控端。假设:设备 b 拥有本地相机设备,分布式组网中的设备 a 可以分布式调用设备 b 的相机设备。
这种场景下,设备 a 是主控端,设备 b 是被控端,两个设备通过软总线进行交互。
virtualcamerahal:作为硬件适配层(hal)的一部分,负责和分布式相机框架中的主控端交互,将主控端 cameraframwork 下发的指令传输给分布式相机框架的 sourcemgr 处理。
sourcemgr:通过软总线将控制信息传递给被控端的 cameraclient。
cameraclient:直接通过调用被控端 cameraframwork 的接口来完成对设备 b 相机的控制。
最后,从设备 b 反馈的预览图像数据会通过分布式相机框架的 channelsink 回传到设备 a 的 hal 层,进而反馈给应用。通过这种方式,设备 a 的应用就可以像使用本地设备一样使用设备 b 的相机。
相关名词介绍:
主控端(source):控制端,通过调用分布式相机能力,使用被控端的摄像头进行预览、拍照、录像等功能。
被控端(sink):被控制端,通过分布式相机接收主控端的命令,使用本地摄像头为主控端提供图像数据。
现在我们要实现分布式相机,在主控端调用被控端相机,实现远程操作相机,开发此应用的具体需求:
支持本地相机的预览、拍照、保存相片、相片缩略图、快速查看相片、切换摄像头(如果一台设备上存在多个摄像头时)。
同一网络下,支持分布式 pin 码认证,远程连接。
自由切换本地相机和远程相机。
ui 草图
从草图上看,我们简单的明应用 ui 布局的整体内容:
顶部右上角有个切换设备的按钮,点击弹窗显示设备列表,可以实现设备认证与设备切换功能。
中间使用 xcomponent 组件实现的相机预览区域。
底部分为如下三个部分。
具体如下:
相机缩略图:显示当前设备媒体库中最新的图片,点击相机缩略图按钮可以查看相关的图片。
拍照:点击拍照按钮,将相机当前帧保存到本地媒体库中。
切换摄像头:如果一台设备有多个摄像头时,例如相机有前后置摄像头,点击切换后会将当前预览的页面切换到另外一个摄像头的图像。
实现效果
开发环境
    如下:
系统:openharmony 3.2 beta4/openharmony 3.2 beta5
设备:dayu200
ide:deveco studio 3.0 release ,build version: 3.0.0.993, built on september 4, 2022
sdk:full_3.2.9.2
开发模式:stage
开发语言:ets
开发实践
    本篇主要在应用层的角度实现分布式相机,实现远程相机与实现本地相机的流程相同,只是使用的相机对象不同,所以我们先完成本地相机的开发,再通过参数修改相机对象来启动远程相机。
①创建项目
②权限声明
(1)module.json 配置权限
说明: 在 module 模块下添加权限声明,权限的详细说明
https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/permission-list.mdrequestpermissions: [  {    name: ohos.permission.require_form  },  {    name: ohos.permission.media_location  },  {    name: ohos.permission.modify_audio_settings  },  {    name: ohos.permission.read_media  },  {    name: ohos.permission.write_media  },  {    name: ohos.permission.get_bundle_info_privileged  },  {    name: ohos.permission.camera  },  {    name: ohos.permission.microphone  },  {    name: ohos.permission.distributed_datasync  }]  
(2)在 index.ets 页面的初始化 abouttoappear() 申请权限
代码如下:
let permissionlist: array = [  ohos.permission.media_location,  ohos.permission.read_media,  ohos.permission.write_media,  ohos.permission.camera,  ohos.permission.microphone,  ohos.permission.distributed_datasync] async abouttoappear() {    console.info(`${tag} abouttoappear`)    globalthis.cameraabilitycontext.requestpermissionsfromuser(permissionlist).then(async (data) => {      console.info(`${tag} data permissions: ${json.stringify(data.permissions)}`)      console.info(`${tag} data authresult: ${json.stringify(data.authresults)}`)      // 判断授权是否完成      let resultcount: number = 0      for (let result of data.authresults) {        if (result === 0) {          resultcount += 1        }      }      if (resultcount === permissionlist.length) {        this.ispermissions = true      }      await this.initcamera()      // 获取缩略图      this.mcameraservice.getthumbnail(this.functionbackimpl)    })  }这里有个获取缩略图的功能,主要是获取媒体库中根据时间排序,获取最新拍照的图片作为当前需要显示的缩略图,实现此方法在后面说 cameraservice 类的时候进行详细介绍。 注意:如果首次启动应用,在授权完成后需要加载相机,则建议授权放在启动页完成,或者在调用相机页面之前添加一个过渡页面,主要用于完成权限申请和启动相机的入口,否则首次完成授权后无法显示相机预览,需要退出应用再重新进入才可以正常预览,这里先简单说明下,文章后续会在问题环节详细介绍。  
③ui 布局
说明:ui 如前面截图所示,实现整体页面的布局。 页面中主要使用到 xcomponent 组件,用于 egl/opengles 和媒体数据写入,并显示在 xcomponent 组件。
参看:xcomponent 详细介绍
https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.mdonload():xcomponent 插件加载完成时的回调,在插件完成时可以获取**id并初始化相机。  
xcomponentcontroller:xcomponent 组件控制器,可以绑定至 xcomponent 组件,通过 getxcomponent/**aceid() 获取 xcomponent 对应的/**aceid。
代码如下:
@state @watch('selectedindexchange') selectindex: number = 0  // 设备列表  @state devices: array = []  // 设备选择弹窗  private dialogcontroller: customdialogcontroller = new customdialogcontroller({    builder: devicedialog({      devicelist: $devices,      selectindex: $selectindex,    }),    autocancel: true,    alignment: dialogalignment.center  })  @state curpicturewidth: number = 70  @state curpictureheight: number = 70  @state curthumbnailwidth: number = 70  @state curthumbnailheight: number = 70  @state curswitchangle: number = 0  @state id: string = ''  @state thumbnail: image.pixelmap = undefined  @state resourceuri: string = ''  @state isswitchdeviceing: boolean = false // 是否正在切换相机  private isinitcamera: boolean = false // 是否已初始化相机  private ispermissions: boolean = false // 是否完成授权  private componentcontroller: xcomponentcontroller = new xcomponentcontroller()  private mcurdeviceid: string = constant.local_device_id // 默认本地相机  private mcurcameraindex: number = 0 //  默认相机列表中首个相机  private mcameraservice = cameraservice.getinstance()  build() {    stack({ aligncontent: alignment.center }) {      column() {        row({ space: 20 }) {          image($r('app.media.ic_camera_public_setting'))            .width(40)            .height(40)            .margin({              right: 20            })            .objectfit(imagefit.contain)            .onclick(() => {              console.info(`${tag} click distributed auth.`)              this.showdialog()            })        }        .width('100%')        .height('5%')        .margin({          top: 20,          bottom: 20        })        .alignitems(verticalalign.center)        .justifycontent(flexalign.end)        column() {          xcomponent({            id: 'componentid',            type: 'xxxxace',            controller: this.componentcontroller          }).onload(async () => {            console.info(`${tag} xcomponent onload is called`)            this.componentcontroller.setxcomponentxxxxacesize({              xxxxwidth: resolution.default_width,              xxxxaceheight: resolution.default_height            })            this.id = this.componentcontroller.getxcomponentxxxxaceid()            console.info(`${tag} id: ${this.id}`)            await this.initcamera()          }).height('100%')            .width('100%')        }        .width('100%')        .height('75%')        .margin({          bottom: 20        })        row() {          column() {            image(this.thumbnail != undefined ? this.thumbnail : $r('app.media.screen_pic'))              .width(this.curthumbnailwidth)              .height(this.curthumbnailheight)              .objectfit(imagefit.cover)              .onclick(async () => {                console.info(`${tag} launch bundle com.ohos.photos`)                await globalthis.cameraabilitycontext.startability({                  parameters: { uri: 'photodetail' },                  bundlename: 'com.ohos.photos',                  abilityname: 'com.ohos.photos.mainability'                })                animateto({                  duration: 200,                  curve: curve.easeinout,                  delay: 0,                  iterations: 1,                  playmode: playmode.reverse,                  onfinish: () => {                    animateto({                      duration: 100,                      curve: curve.easeinout,                      delay: 0,                      iterations: 1,                      playmode: playmode.reverse                    }, () => {                      this.curthumbnailwidth = 70                      this.curthumbnailheight = 70                    })                  }                }, () => {                  this.curthumbnailwidth = 60                  this.curthumbnailheight = 60                })              })          }          .width('33%')          .alignitems(horizontalalign.start)          column() {            image($r('app.media.icon_picture'))              .width(this.curpicturewidth)              .height(this.curpictureheight)              .objectfit(imagefit.cover)              .alignrules({                center: {                  align: verticalalign.center,                  anchor: 'center'                }              })              .onclick(() => {                this.takepicture()                animateto({                  duration: 200,                  curve: curve.easeinout,                  delay: 0,                  iterations: 1,                  playmode: playmode.reverse,                  onfinish: () => {                    animateto({                      duration: 100,                      curve: curve.easeinout,                      delay: 0,                      iterations: 1,                      playmode: playmode.reverse                    }, () => {                      this.curpicturewidth = 70                      this.curpictureheight = 70                    })                  }                }, () => {                  this.curpicturewidth = 60                  this.curpictureheight = 60                })              })          }          .width('33%')          column() {            image($r('app.media.icon_switch'))              .width(50)              .height(50)              .objectfit(imagefit.cover)              .rotate({                x: 0,                y: 1,                z: 0,                angle: this.curswitchangle              })              .onclick(() => {                this.switchcamera()                animateto({                  duration: 500,                  curve: curve.easeinout,                  delay: 0,                  iterations: 1,                  playmode: playmode.reverse,                  onfinish: () => {                    animateto({                      duration: 500,                      curve: curve.easeinout,                      delay: 0,                      iterations: 1,                      playmode: playmode.reverse                    }, () => {                      this.curswitchangle = 0                    })                  }                }, () => {                  this.curswitchangle = 180                })              })          }          .width('33%')          .alignitems(horizontalalign.end)        }        .width('100%')        .height('10%')        .justifycontent(flexalign.spacebetween)        .alignitems(verticalalign.center)        .padding({          left: 40,          right: 40        })      }      .height('100%')      .width('100%')      .padding(10)      if (this.isswitchdeviceing) {        column() {          image($r('app.media.load_switch_camera'))            .width(400)            .height(306)            .objectfit(imagefit.fill)          text($r('app.string.switch_camera'))            .width('100%')            .height(50)            .fontsize(16)            .fontcolor(color.white)            .align(alignment.center)        }        .width('100%')        .height('100%')        .backgroundcolor(color.black)        .justifycontent(flexalign.center)        .alignitems(horizontalalign.center)        .onclick(() => {        })      }    }    .height('100%')    .backgroundcolor(color.black)  }(1)启动系统相册  
说明:用户点击图片缩略图时需要启动图片查看,这里直接打开系统相册,查看相关的图片。
代码如下:
await globalthis.cameraabilitycontext.startability({                  parameters: { uri: 'photodetail' },                  bundlename: 'com.ohos.photos',                  abilityname: 'com.ohos.photos.mainability'                })  
④相机服务 cameraservice.ts
(1)cameraservice 单例模式,用于提供操作相机相关的业务
代码如下:
private static instance: cameraservice = null    private constructor() {        this.mthumbnailgetter = new thumbnailgetter()    }    /**     * 单例     */    public static getinstance(): cameraservice {        if (this.instance === null) {            this.instance = new cameraservice()        }        return this.instance    }(2)初始化相机 说明:通过媒体相机提供的 api(@ohos.multimedia.camera)getcameramanager() 获取相机管理对象 cameramanager,并注册相机状态变化监听器,实时更新相机状态。  
同时通过 cameramanager…getsupportedcameras() 获取前期支持的相机设备集合,这里的相机设备包括当前设备上安装的相机设备和远程设备上的相机设备。
代码如下:
/**     * 初始化     */    public async initcamera(): promise {        console.info(`${tag} initcamera`)        if (this.mcameramanager === null) {            this.mcameramanager = await camera.getcameramanager(globalthis.cameraabilitycontext)            // 注册监听相机状态变化            this.mcameramanager.on('camerastatus', (camerastatusinfo) => {                console.info(`${tag} camera status: ${json.stringify(camerastatusinfo)}`)            })            // 获取相机列表            let cameras: array = await this.mcameramanager.getsupportedcameras()            if (cameras) {                this.mcameracount = cameras.length                console.info(`${tag} mcameracount: ${this.mcameracount}`)                if (this.mcameracount === 0) {                    return this.mcameracount                }                for (let i = 0; i  0) {            console.info(`${tag} displaycameradevice has mcameramap`)            // 判断相机列表中是否已经存在此相机            let isexist: boolean = false            for (let item of this.mcameramap.get(key)) {                if (item.cameraid === cameradevice.cameraid) {                    isexist = true                    break                }            }            // 添加列表中没有的相机            if (!isexist) {                console.info(`${tag} displaycameradevice not exist , push ${cameradevice.cameraid}`)                this.mcameramap.get(key).push(cameradevice)            } else {                console.info(`${tag} displaycameradevice has existed`)            }        } else {            let cameras: array = []            console.info(`${tag} displaycameradevice push ${cameradevice.cameraid}`)            cameras.push(cameradevice)            this.mcameramap.set(key, cameras)        }    }  
(3)创建相机输入流
说明:cameramanager.createcamerainput() 可以创建相机输出流 camerainput 实例,camerainput 是在 capturesession 会话中使用的相机信息,支持打开相机、关闭相机等能力。 代码如下:
/**     * 创建相机输入流     * @param cameraindex 相机下标     * @param deviceid 设备id     */    public async createcamerainput(cameraindex?: number, deviceid?: string) {        console.info(`${tag} createcamerainput`)        if (this.mcameramanager === null) {            console.error(`${tag} mcameramanager is null`)            return        }        if (this.mcameracount  {                console.info(`${tag} createpreviewoutput camera frame end`)                callback.onframeend()            })            this.mpreviewoutput.on('error', (error) => {                console.error(`${tag} createpreviewoutput error: ${error}`)            })        } catch (err) {            console.error(`${tag} failed to createpreviewoutput ${err}`)        }    }   
(5)拍照输出流
说明:cameramanager.createphotooutput() 可以创建拍照输出对象  photooutput,photooutput 继承 cameraoutput 在拍照会话中使用的输出信息,支持拍照、判断是否支持镜像拍照、释放资源、监听拍照开始、拍照帧输出捕获、拍照结束等能力。
代码如下:
/**     * 创建拍照输出流     */    public async createphotooutput(functioncallback: functioncallback) {        console.info(`${tag} createphotooutput`)        if (!this.mcameramanager) {            console.error(`${tag} createphotooutput mcameramanager is null`)            return        }        // 通过宽、高、图片格式、容量创建imagereceiver实例        const receiver: image.imagereceiver = image.createimagereceiver(resolution.default_width, resolution.default_height, image.imageformat.jpeg, 8)        const imageid: string = await receiver.getreceivingxxxxaceid()        console.info(`${tag} createphotooutput imageid: ${imageid}`)        let cameraoutputcap = await this.mcameramanager.getsupportedoutputcapability(this.mcurcameradevice)        console.info(`${tag} createphotooutput cameraoutputcap ${cameraoutputcap}`)        if (!cameraoutputcap) {            console.error(`${tag} createphotooutput getsupportedoutputcapability error}`)            return        }        let photoprofilesarray = cameraoutputcap.photoprofiles        let photoprofiles: camera.profile        if (!photoprofilesarray || photoprofilesarray.length  {            console.error(`${tag} capturesession error ${json.stringify(error)}`)        })        try {            await this.mcapturesession?.beginconfig()            await this.mcapturesession?.addinput(this.mcamerainput)            if (this.mphotooutput != null) {                console.info(`${tag} createsession addoutput photooutput`)                await this.mcapturesession?.addoutput(this.mphotooutput)            }            await this.mcapturesession?.addoutput(this.mpreviewoutput)        } catch (err) {            if (err) {                console.error(`${tag} createsession beginconfig fail err:${json.stringify(err)}`)            }        }        try {            await this.mcapturesession?.commitconfig()        } catch (err) {            if (err) {                console.error(`${tag} createsession commitconfig fail err:${json.stringify(err)}`)            }        }        try {            await this.mcapturesession?.start()        } catch (err) {            if (err) {                console.error(`${tag} createsession start fail err:${json.stringify(err)}`)            }        }        console.info(`${tag} createsession mcapturesession start`)    }  ⑤拍照 说明:通过 photooutput.capture() 可以实现拍照功能。 代码如下:    /**     * 拍照     */    public async takepicture() {        console.info(`${tag} takepicture`)        if (!this.mcapturesession) {            console.info(`${tag} takepicture session is release`)            return        }        if (!this.mphotooutput) {            console.info(`${tag} takepicture mphotooutput is null`)            return        }        try {            const photocapturesetting: camera.photocapturesetting = {                quality: camera.qualitylevel.quality_level_high,                rotation: camera.imagerotation.rotation_0,                location: {                    latitude: 0,                    longitude: 0,                    altitude: 0                },                mirror: false            }            await this.mphotooutput.capture(photocapturesetting)        } catch (err) {            console.error(`${tag} takepicture err:${json.stringify(err)}`)        }    }⑥保存图片 savecameraasset  
说明:savecameraasset.ts 主要用于保存拍摄的图片,即是调用拍照操作后,会触发图片接收监听器,在将图片的字节流进行写入本地文件操作。
代码如下:
/** * 保存相机拍照的资源 */import image from '@ohos.multimedia.image'import medialibrary from '@ohos.multimedia.medialibrary'import { functioncallback } from '../model/cameraservice'import datetimeutil from '../utils/datetimeutil'import fileio from '@ohos.file.fs';import thumbnailgetter from '../model/thumbnailgetter'let photouri: string // 图片地址const tag: string = 'savecameraasset'export default class savecameraasset {    private lastsavetime: string = ''    private saveindex: number = 0    constructor() {    }    public getphotouri(): string {        console.info(`${tag} getphotouri = ${photouri}`)        return photouri    }    /**     *  保存拍照图片     * @param imagereceiver 图像接收对象     * @param thumbwidth 缩略图宽度     * @param thumbheight 缩略图高度     * @param callback 回调     */    public saveimage(imagereceiver: image.imagereceiver, thumbwidth: number, thumbheight: number, thumbnailgetter :thumbnailgetter, callback: functioncallback) {        console.info(`${tag} saveimage`)        const mdatetimeutil = new datetimeutil()        const filekeyobj = medialibrary.filekey        const mediatype = medialibrary.mediatype.image        let buffer = new arraybuffer(4096)        const media = medialibrary.getmedialibrary(globalthis.cameraabilitycontext) // 获取媒体库实例        // 接收图片回调        imagereceiver.on('imagearrival', async () => {            console.info(`${tag} saveimage imagearrival`)            // 使用当前时间命名            const displayname = this.checkname(`img_${mdatetimeutil.getdate()}_${mdatetimeutil.gettime()}`) + '.jpg'            console.info(`${tag} displayname = ${displayname}}`)            imagereceiver.readnextimage((err, imageobj: image.image) => {                if (imageobj === undefined) {                    console.error(`${tag} saveimage failed to get valid image error = ${err}`)                    return                }                // 根据图像的组件类型从图像中获取组件缓存 4-jpeg类型                imageobj.getcomponent(image.componenttype.jpeg, async (errmsg, imgcomponent) => {                    if (imgcomponent === undefined) {                        console.error(`${tag} getcomponent failed to get valid buffer error = ${errmsg}`)                        return                    }                    if (imgcomponent.bytebuffer) {                        console.info(`${tag} getcomponent imgcomponent.bytebuffer ${imgcomponent.bytebuffer}`)                        buffer = imgcomponent.bytebuffer                    } else {                        console.info(`${tag} getcomponent imgcomponent.bytebuffer is undefined`)                    }                    await imageobj.release()                })            })            let publicpath:string = await media.getpublicdirectory(medialibrary.directorytype.dir_camera)            console.info(`${tag} saveimage publicpath = ${publicpath}`)            //  创建媒体资源 返回提供封装文件属性            const datauri : medialibrary.fileasset = await media.createasset(mediatype, displayname, publicpath)            // 媒体文件资源创建成功,将拍照的数据写入到媒体资源            if (datauri !== undefined) {                photouri = datauri.uri                console.info(`${tag} saveimage photouri: ${photouri}`)                const args = datauri.id.tostring()                console.info(`${tag} saveimage id: ${args}`)                //  通过id查找媒体资源                const fetchoptions:medialibrary.mediafetchoptions = {                    selections : `${filekeyobj.id} = ?`,                    selectionargs : [args]                }                console.info(`${tag} saveimage fetchoptions: ${json.stringify(fetchoptions)}`)                const fetchfileresult = await media.getfileassets(fetchoptions)                const fileasset = await fetchfileresult.getallobject() // 获取文件检索结果中的所有文件资                if (fileasset != undefined) {                    fileasset.foreach((datainfo) => {                        datainfo.open('rw').then((fd) => { // rw是读写方式打开文件 获取fd                            console.info(`${tag} saveimage datainfo.open called. fd: ${fd}`)                            // 将缓存图片流写入资源                            fileio.write(fd, buffer).then(() => {                                console.info(`${tag} saveimage fileio.write called`)                                datainfo.close(fd).then(() => {                                    console.info(`${tag} saveimage datainfo.close called`)                                    // 获取资源缩略图                                    thumbnailgetter.getthumbnailinfo(thumbwidth, thumbheight, photouri).then((thumbnail => {                                        if (thumbnail === undefined) {                                            console.error(`${tag} saveimage getthumbnailinfo undefined`)                                            callback.oncapturefailure()                                        } else {                                            console.info(`${tag} photouri: ${photouri} pixelbytesnumber: ${thumbnail.getpixelbytesnumber()}`)                                            callback.oncapturesuccess(thumbnail, photouri)                                        }                                    }))                                }).catch(error => {                                    console.error(`${tag} saveimage close is error ${json.stringify(error)}`)                                })                            })                        })                    })                } else {                    console.error(`${tag} saveimage fileasset: is null`)                }            } else {                console.error(`${tag} saveimage photouri is null`)            }        })    }    /**     * 检测文件名称     * @param filename 文件名称     * 如果同一时间有多张图片,则使用时间_index命名     */    private checkname(filename: string): string {        if (this.lastsavetime == filename) {            this.saveindex++            return `${filename}_${this.saveindex}`        }        this.lastsavetime = filename        this.saveindex = 0        return filename    }}   
⑦获取缩略图
说明:主要通过获取当前媒体库中根据时间排序,获取最新的图片并缩放图片大小后返回。
代码如下:
/**     * 获取缩略图     * @param callback     */    public getthumbnail(callback: functioncallback) {        console.info(`${tag} getthumbnail`)        this.mthumbnailgetter.getthumbnailinfo(resolution.thumbnail_width, resolution.thumbnail_height).then((thumbnail) => {            console.info(`${tag} getthumbnail thumbnail = ${thumbnail}`)            callback.thumbnail(thumbnail)        })    }(1)thumbnailgetter.ts 说明: 实现获取缩略图的对象。 代码如下:/** * 缩略图处理器 */import medialibrary from '@ohos.multimedia.medialibrary';import image from '@ohos.multimedia.image';const tag: string = 'thumbnailgetter'export default class thumbnailgetter {    public async getthumbnailinfo(width: number, height: number, uri?: string): promise {        console.info(`${tag} getthumbnailinfo`)        // 文件关键信息        const filekeyobj = medialibrary.filekey        // 获取媒体资源公共路径        const media: medialibrary.medialibrary = medialibrary.getmedialibrary(globalthis.cameraabilitycontext)        let publicpath: string = await media.getpublicdirectory(medialibrary.directorytype.dir_camera)        console.info(`${tag} publicpath = ${publicpath}`)        let fetchoptions: medialibrary.mediafetchoptions = {            selections: `${filekeyobj.relative_path}=?`, // 检索条件 relative_path-相对公共目录的路径            selectionargs: [publicpath] // 检索条件值        }        if (uri) {            fetchoptions.uri = uri // 文件的uri        } else {            fetchoptions.order = filekeyobj.date_added + ' desc'        }        console.info(`${tag} getthumbnailinfo fetchoptions :  ${json.stringify(fetchoptions)}}`)        const fetchfileresult = await media.getfileassets(fetchoptions) // 文件检索结果集        const count = fetchfileresult.getcount()        console.info(`${tag} count = ${count}`)        if (count == 0) {            return undefined        }        // 获取结果集合中的最后一张图片        const lastfileasset = await fetchfileresult.getfirstobject()        if (lastfileasset == null) {            console.error(`${tag} getthumbnailinfo lastfileasset is null`)            return undefined        }        const thumbnailpixelmap = lastfileasset.getthumbnail({            width: width,            height: height        })        console.info(`${tag} getthumbnailinfo thumbnailpixelmap ${json.stringify(thumbnailpixelmap)}}`)        return thumbnailpixelmap    }}⑧释放资源 说明:在相机设备切换时,如前后置摄像头切换或者不同设备之间的摄像头切换时都需要先释放资源,再重新创建新的相机会话才可以正常运行,释放的资源包括:释放相机输入流、预览输出流、拍照输出流、会话。 代码如下:/**     * 释放相机输入流     */    public async releasecamerainput() {        console.info(`${tag} releasecamerainput`)        if (this.mcamerainput) {            try {                await this.mcamerainput.release()            } catch (err) {                console.error(`${tag} releasecamerainput ${err}}`)            }            this.mcamerainput = null        }    }/**     * 释放预览输出流     */    public async releasepreviewoutput() {        console.info(`${tag} releasepreviewoutput`)        if (this.mpreviewoutput) {            await this.mpreviewoutput.release()            this.mpreviewoutput = null        }    }/**     * 释放拍照输出流     */    public async releasephotooutput() {        console.info(`${tag} releasephotooutput`)        if (this.mphotooutput) {            await this.mphotooutput.release()            this.mphotooutput = null        }    }    public async releasesession() {        console.info(`${tag} releasesession`)        if (this.mcapturesession) {            await this.mcapturesession.stop()            console.info(`${tag} releasesession stop`)            await this.mcapturesession.release()            console.info(`${tag} releasesession release`)            this.mcapturesession = null            console.info(`${tag} releasesession null`)        }    }  
至此,总结下,需要实现相机预览、拍照功能:
通过 camera 媒体 api 提供的 camera.getcameramanager() 获取 cameramanager 相机管理类。
通过相机管理类型创建相机预览与拍照需要的输入流(createcamerainput)和输出流(createpreviewoutput、createphotooutput),同时创建相关会话管理(createcapturesession)
将输入流、输出流添加到会话中,并启动会话
拍照可以直接使用 photooutput.capture 执行拍照,并将拍照结果保存到媒体
在退出相机应用时,需要注意释放相关的资源。
因为分布式相机的应用开发内容比较长,这篇只说到主控端相机设备预览与拍照功能,下一篇会将结合分布式相关内容完成主控端设备调用远程相机进行预览的功能。  


微控制器集成电路的9种外接振荡元件引脚电路
风云人物谈半导体产业发展趋势
ADI针对直接变频接收机的优化方案
三星电子将加强新一代神经网处理装置技术 如果有必要也可以实行大型并购
智能虚拟助理知得信任吗?
OpenHarmony上实现分布式相机
中科院宣布介入光刻机研发之后,ASML宣布将在中国加大布局
针对大型工地的管理系统介绍
OLED阵营持续壮大 但市场占有率不高
小米6来了 还有小米公寓要发售了
工业控制设备之变频器的应用情况分析
WisBlock PAR 监测应用指南
二极管在单片机RC复位电路中的作用
东芝以180亿美元转手芯片业务给贝恩财团,贝恩表示很满意
RFID技术在电子车牌智慧交通中的应用
金泰克LPDDR3/LPDDR4两款产品主要用于移动设备的内存芯片
三星note8什么时候上市?三星note8最新消息:三星note8就要来了,三星Note8:首发骁龙836+4K屏+6000+
电气控制柜UL508A认证
384X系列电流型PWM控制器的特点及设计注意事项
ATM地址注册/ATM的虚连接