【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);
    }
  }
相关推荐
IMdive2 小时前
OpenHarmony鸿蒙远程数据库连接应用开发指南
数据库·华为·harmonyos
前端不太难2 小时前
AI 如何改变传统 鸿蒙App 的信息架构
人工智能·架构·harmonyos
无巧不成书02182 小时前
KMP适配鸿蒙开发实战|从0到1搭建可运行工程
javascript·华为·harmonyos·kmp
无巧不成书02183 小时前
Kotlin Multiplatform (KMP) 鸿蒙开发整合实战|2026最新方案
android·开发语言·kotlin·harmonyos·kmp
盐焗西兰花3 小时前
鸿蒙学习实战之路-STG系列(3/11)-用户授权管理详解
服务器·学习·harmonyos
键盘鼓手苏苏3 小时前
Flutter for OpenHarmony:injector 轻量级依赖注入库(比 GetIt 更简单的选择) 深度解析与鸿蒙适配指南
css·网络·flutter·华为·rust·harmonyos
●VON3 小时前
HarmonyOS应用开发实战(基础篇)Day07-《登录注册页面》
学习·安全·华为·harmonyos·von
不爱吃糖的程序媛4 小时前
Flutter性能监控插件鸿蒙适配实战指南
flutter·harmonyos
无巧不成书02184 小时前
React Native 鸿蒙系统(HarmonyOS/OpenHarmony)适配全景指南
react native·react.js·华为·开源·交互·harmonyos
星空22234 小时前
【HarmonyOS】React Native of HarmonyOS实战:手势组合与协同
react native·华为·harmonyos