【HarmonyOS】鸿蒙应用唤起系统相机拍照

【HarmonyOS】鸿蒙应用唤起系统相机拍照

方案一:

官方推荐的方式,使用CameraPicker来调用安全相机进行拍照。

dart 复制代码
    let pathDir = getContext().filesDir;
    let fileName = `${new Date().getTime()}`
    let filePath = pathDir + `/${fileName}.tmp`
    fileIo.createRandomAccessFileSync(filePath, fileIo.OpenMode.CREATE);

    let uri = fileUri.getUriFromPath(filePath);
    let pickerProfile: picker.PickerProfile = {
      cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK,
      saveUri: uri // 用于保存图片
    };
    let result: picker.PickerResult =
      await picker.pick(getContext(), [picker.PickerMediaType.PHOTO],
        pickerProfile);
    console.info(`picker resultCode: ${result.resultCode},resultUri: ${result.resultUri},mediaType: ${result.mediaType}`);
    if (result.resultCode == 0) {
      if (result.mediaType === picker.PickerMediaType.PHOTO) {
        this.imgSrc = result.resultUri;
      } 
    }

注意:
在应用调试时,开发者需在release模式下调用系统相机(CameraPicker)。
由于系统限制了debug模式下不允许调试release应用,在debug模式下调用系统相机,将导致异常。

方案二:

使用startAbility拉起相机系统应用,通过want接收回调信息。

dart 复制代码
  private async thirdPartyCall(supportMultiMode: boolean) {
    this.isCrop = false;
    console.log("thirdPartyCall savaPath=" + this.savePath);
    // 拉起拍照功能
    let want: Want = {
      "action": 'ohos.want.action.imageCapture',
      "parameters": {
        supportMultiMode: supportMultiMode,
        // 回调包名很重要,若不匹配将无法获取返回图片Uri的操作权限
        callBundleName: "com.example.persontest"
      }
    };
    // 获取图片uri
    if (this.context) {
      let result: common.AbilityResult = await this.context.startAbilityForResult(want);
      let params = result?.want?.parameters as Record<string, string | number>
      let imagePathSrc = params?.resourceUri as string;
      console.info(this.TAG, 'thirdPartyCall imagePathSrc= ' + imagePathSrc);
      console.info(this.TAG, 'thirdPartyCall params= ' + JSON.stringify(params));
      await this.getImage(imagePathSrc);
    }
  }
相关推荐
ai安歌8 小时前
鸿蒙PC:Qt适配OpenHarmony实战【取色间】:RGB 滑动调整、HEX 展示和颜色预览
qt·华为·harmonyos
lqj_本人8 小时前
鸿蒙electron跨端框架PC想法卡片实战:把零散灵感做成能继续展开的卡片流
华为·electron·harmonyos
专注前端30年9 小时前
2025-2026 大厂 Vue2Vue3 高频面试题 Top100
百度·华为·大厂面试题·阿里·前端vue2/3
lqj_本人11 小时前
鸿蒙electron跨端框架PC浮签实战:做一面轻巧但能回找的桌面便签墙
华为·harmonyos
ai安歌12 小时前
鸿蒙PC:Qt适配OpenHarmony实战【人名录】:单机联系人卡片,不读系统通讯录也能演示详情联动
数据库·qt·harmonyos
lqj_本人13 小时前
鸿蒙electron跨端框架PC简序实战:把轻任务、优先级和截止时间塞进一张桌面清单
华为·harmonyos
想你依然心痛13 小时前
HarmonyOS 6 悬浮导航 + 沉浸光感:打造鸿蒙智能体驱动的沉浸式智能家居控制中枢
华为·ar·智能家居·harmonyos·智能体
lqj_本人13 小时前
鸿蒙PC:Qt适配OpenHarmony实战【花账】:从一笔支出开始,做一个本地记账小应用
数据库·qt·harmonyos
递归40414 小时前
ofdkit-harmony 0.2.0 发布:鸿蒙原生 OFD 阅读库,已上架 ohpm
开源·harmonyos·arkts·ofd·ohpm
nashane14 小时前
HarmonyOS 6学习:SoundPool音频防抖与Web长截图时序重构
学习·音视频·harmonyos·harmonyos 5