HarmonyOS鸿蒙Next中应用如何唤起系统相机拍照和录像?

HarmonyOS鸿蒙Next中应用如何唤起系统相机拍照和录像?

鸿蒙应用如何唤起系统相机拍照和录像?

4 回复

使用相机选择器:cameraPicker

import { cameraPicker } from '@kit.CameraKit';
import { camera } from '@kit.CameraKit';
import { BusinessError } from '@kit.BasicServicesKit';
async function demo(context: Context) {
  try {
    let pickerProfile: cameraPicker.PickerProfile = {
      cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK
    };
    let pickerResult: cameraPicker.PickerResult = await cameraPicker.pick(context,
      [cameraPicker.PickerMediaType.PHOTO, cameraPicker.PickerMediaType.VIDEO], pickerProfile);
    console.info("the pick pickerResult is:" + JSON.stringify(pickerResult));
  } catch (error) {
    let err = error as BusinessError;
    console.error(`the pick call failed. error code: ${err.code}`);
  }
}

PickerMediaType

枚举,相机选择器的媒体类型。

名称 说明
PHOTO ‘photo’ 拍照模式。
VIDEO ‘video’ 录制模式。

项目地址:https://gitcode.com/HarmonyOS_Samples/camera-picker

更多关于HarmonyOS鸿蒙Next中应用如何唤起系统相机拍照和录像?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


https://alliance-communityfile-drcn.dbankcdn.com/FileServer/getFile/cmtybbs/224/864/695/EC723465A02114AE84031BBFCB348AEB:E1EB1ADBCDD1926E81E3ECD6BF970CC3C846E689A4194DC3C235B0CF80E6AD15.20251222231136.10604452892018691087895779406316:50001231000000:2800:E97C2A82E1DB7DE5FA3C5B03C80714C54935B28A1C30B647A9DC29877670C1EA.png

方案一:

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

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;
  } 
}

方案二:

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

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);
  }
}

在HarmonyOS Next中,通过@ohos.multimedia.camera@ohos.file.picker模块实现。使用PhotoViewPickerVideoViewPicker拉起系统相机界面。配置PhotoSelectOptionsVideoSelectOptions定义参数,如选择媒体数量。调用select()方法获取文件URI。需在module.json5中声明ohos.permission.READ_IMAGEVIDEOohos.permission.CAMERA权限。

在HarmonyOS Next中,应用可以通过Want机制和系统提供的Camera相关Ability来唤起系统相机进行拍照和录像。核心步骤如下:

  1. 权限声明:首先在module.json5配置文件的requestPermissions字段中声明相机权限。

    "requestPermissions": [
      {
        "name": "ohos.permission.CAMERA"
      }
    ]
    
  2. 动态权限申请:在运行时代码中,使用abilityAccessCtrl相关API检查并申请ohos.permission.CAMERA权限。

  3. 构造Want并启动系统相机

    • 拍照:通过Want指定系统相机Ability("action.camera.capture")并设置参数"mode""photo"
    • 录像:通过Want指定系统相机Ability("action.camera.capture")并设置参数"mode""video"。 可以同时设置输出文件URI等额外参数。
  4. 处理返回结果:在onResult回调中接收拍摄完成后的文件URI等信息。

关键代码示例(ArkTS)

import common from '@ohos.app.ability.common';
import wantConstant from '@ohos.app.ability.wantConstant';
import camera from '@ohos.multimedia.camera';

// 1. 动态权限申请(此处略去具体代码)

// 2. 构造Want并启动相机(以拍照为例)
let context: common.UIAbilityContext = ...; // 获取UIAbilityContext
let want: Record<string, Object> = {
  action: 'action.camera.capture',
  parameters: {
    mode: 'photo', // 'video' 表示录像
    // 可选:指定输出文件Uri
    // photoOutputUri: 'file://...',
    // videoOutputUri: 'file://...'
  }
};
context.startAbilityForResult(want).then((data) => {
  // 3. 处理返回结果
  if (data?.resultCode === wantConstant.ResultCode.RESULT_OK && data.want?.parameters) {
    let uri = data.want.parameters['photoOutputUri']; // 拍照返回
    // let uri = data.want.parameters['videoOutputUri']; // 录像返回
    // 使用uri处理媒体文件
  }
}).catch((err) => {
  console.error('启动相机失败: ' + JSON.stringify(err));
});

注意事项

  • 确保设备上存在可用的系统相机应用。
  • 录像功能可能需要额外声明麦克风权限(ohos.permission.MICROPHONE)。
  • 输出文件URI可选,若不指定,系统会生成默认路径的文件。
  • 详细参数和错误处理请参考官方API文档中WantCamera相关说明。

这种方式直接调用系统相机,功能完整且体验一致。如果需要对相机进行更底层的控制(如预览、自定义参数),则需使用CameraKit等底层相机API。

回到顶部