【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);
    }
  }
相关推荐
春卷同学1 小时前
篮球游戏 - Electron for 鸿蒙PC项目实战案例
游戏·electron·harmonyos
赵财猫._.1 小时前
【Flutter x 鸿蒙】第一篇:环境搭建与第一个鸿蒙Flutter应用运行
flutter·华为·harmonyos
春卷同学3 小时前
滑雪游戏 - Electron for 鸿蒙PC项目实战案例
游戏·electron·harmonyos
青瓷看世界4 小时前
鸿蒙开发时AI编程工具codeGenie与Github Copilot的区别
github·copilot·ai编程·harmonyos·codegenie
赵财猫._.4 小时前
【Flutter x 鸿蒙】第二篇:理解Flutter on HarmonyOS的架构设计
flutter·华为·harmonyos
DARLING Zero two♡4 小时前
从数据中心到边缘:基于 openEuler 24.03 LTS SP2 的 K3s 轻量化云原生实战评测
华为·云原生
春卷同学5 小时前
基于Electron开发的跨平台鸿蒙PC剪刀石头布游戏应用
游戏·electron·harmonyos
春卷同学6 小时前
钓鱼大师 - Electron for 鸿蒙PC项目实战案例
javascript·electron·harmonyos
春卷同学6 小时前
基于Electron开发的跨平台鸿蒙PC经典吃豆人游戏
游戏·electron·harmonyos
春卷同学6 小时前
赛车游戏 - Electron for 鸿蒙PC项目实战案例
游戏·electron·harmonyos