【HarmonyOS 5】Invoking the System Camera for Photo and Video Capture in HarmonyOS Applications

简介: 【HarmonyOS 5】Invoking the System Camera for Photo and Video Capture in HarmonyOS Applications


1. Method One: Using CameraPicker (Official Recommended Approach)

This method utilizes the CameraPicker API to invoke the secure system camera for photo and video capture.

Implementation Code:

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 // Path to save the captured image
};
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;
  }
}

Key Notes:

  • Debug vs. Release Mode: The system camera (CameraPicker) must be tested in Release mode during development. Debug mode restricts access to release-only features, causing exceptions.
  • Permissions: Ensure the app has the ohos.permission.CAMERA permission declared in config.json.


2. Method Two: Using startAbility to Launch the Camera App

This method launches the system camera via an ability request (startAbilityForResult) and handles callbacks through Want parameters.

Implementation Code:

private async thirdPartyCall(supportMultiMode: boolean) {
  this.isCrop = false;
  console.log("thirdPartyCall savePath=" + this.savePath);
  
  // Launch camera intent
  let want: Want = {
    "action": 'ohos.want.action.imageCapture',
    "parameters": {
      supportMultiMode: supportMultiMode,
      // Important: Callback bundle name must match to access the returned URI
      callBundleName: "com.example.persontest"
    }
  };
  // Handle result
  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);
  }
}

Key Notes:

  • Callback Bundle Name: The callBundleName parameter must match the app's bundle name to ensure permission to access the returned image URI.
  • Result Handling: The captured media URI is retrieved via result.want.parameters.resourceUri.


Comparison & Recommendations

Feature

CameraPicker (Method 1)

startAbility (Method 2)

Implementation Complexity

Lower (simpler API)

Higher (requires Want handling)

Security

Secure (official API)

Standard system interaction

Compatibility

Recommended for HarmonyOS NEXT

Works with older versions

Media Types

Supports photos and videos

Primarily for photos (customizable)

Debug Restrictions

Requires Release mode for testing

No such restriction

Additional Tips

  1. Video Capture:
  • Modify PickerMediaType.PHOTO to PickerMediaType.VIDEO in CameraPicker for video recording.
  • For startAbility, use ohos.want.action.videoCapture as the action.
  1. Permissions:
  • Declare ohos.permission.CAMERA in config.json for both methods.
  • For video recording, add ohos.permission.MICROPHONE.
  1. Error Handling:
  • Implement robust error checks for URI handling and permission requests.

By following these methods, you can effectively integrate camera functionality into your HarmonyOS application while adhering to system security requirements.

目录
相关文章
|
4月前
|
物联网 开发工具
【HarmonyOS】鸿蒙应用蓝牙功能实现 (二)
【HarmonyOS】鸿蒙应用蓝牙功能实现 (二)
121 9
【HarmonyOS】鸿蒙应用蓝牙功能实现 (二)
|
4月前
|
开发工具
【HarmonyOS 5】Integrating WeChat Sharing into HarmonyOS Applications
【HarmonyOS 5】Integrating WeChat Sharing into HarmonyOS Applications
108 9
|
4月前
|
定位技术 开发工具
【HarmonyOS】鸿蒙应用实现调用系统地图导航或路径规划
【HarmonyOS】鸿蒙应用实现调用系统地图导航或路径规划
148 5
【HarmonyOS】鸿蒙应用实现调用系统地图导航或路径规划
|
4月前
|
机器学习/深度学习 人工智能 自然语言处理
当无人机遇上Agentic AI:新的应用场景及挑战
本文简介了Agentic AI与AI Agents的不同、Agentic无人机的概念、应用场景、以及所面临的挑战
408 5
当无人机遇上Agentic AI:新的应用场景及挑战
|
4月前
|
开发工具
【HarmonyOS】鸿蒙应用蓝牙功能实现(一)
【HarmonyOS】鸿蒙应用蓝牙功能实现(一)
134 8
【HarmonyOS】鸿蒙应用蓝牙功能实现(一)
|
4月前
|
开发工具
【HarmonyOS 5】使用openCustomDialog如何禁止手势关闭的方案
openCustomDialog提供了onWillDismiss回调函数,当用户尝试通过滑动、点击外部、返回键等操作关闭弹窗时,会触发该回调。通过在回调中判断关闭原因并拦截操作,即可实现禁止手势关闭的效果。
125 1
|
4月前
|
传感器 安全 物联网
【HarmonyOS 5】鸿蒙分布式协同应用开发详解
为什么需要分布式协同应用? 首先是因为当今社会,围绕电子产品生态,人们迫切希望,周边的电子设备可以协同操作。例如手机,手表,电视机,汽车,甚至是各种家电产品。 从2015年到如今,手机和pc等老牌电子产品的设备数趋于稳定,其他IoT设备稳步增长。可见人均所拥有的的电子产品的个数,在迅速增加。
160 0
|
4月前
|
前端开发 JavaScript API
【HarmonyOS 5】鸿蒙跨平台开发方案详解(一)
2025年是鸿蒙生态迎来关键发展期。根据前几天的2025 HDC数据显示,鸿蒙原生应用数量已从2024年的2000款增长至5000款,微信鸿蒙版安装量突破1.2亿,公安部交管系统完成全国300城鸿蒙适配。
302 1
|
4月前
|
Dart 前端开发 JavaScript
【HarmonyOS 5】鸿蒙跨平台开发方案详解 (三)
学习曲线、工具支持、代码复用率、热重载能力
166 0
|
4月前
|
监控 JavaScript 开发工具
【HarmonyOS 5】鸿蒙中@State的原理详解
@State 是 HarmonyOS ArkTS 框架中用于管理组件状态的核心装饰器,其核心作用是实现数据驱动 UI 的响应式编程模式。通过将变量标记为 @State,开发者可以确保当状态值发生变化时,依赖该状态的 UI 组件会自动重新渲染,从而保持数据与界面的实时同步。 @State 是 HarmonyOS ArkTS 实现响应式编程的大基础核心,可以说整个V1和V2都是围绕它来进行组合使用。
166 0