HarmonyOS 鸿蒙Next模拟器使用camera kit拉起相机拍照

HarmonyOS 鸿蒙Next模拟器使用camera kit拉起相机拍照 https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-emulator-specification

文档中写模拟器支持Camera Kit拍照,如何实现?

4 回复

通过系统相机拍照和录像(CameraPicker),无需申请相机权限。

import { camera, cameraPicker as picker } from '@kit.CameraKit';
import { fileIo, fileUri } from '@kit.CoreFileKit';

@Entry
@Component
struct Index {
  @State imgSrc: string = '';
  @State videoSrc: string = '';
  createPickerProfile(context: Context): picker.PickerProfile {
    let pathDir = context.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
    };
    return pickerProfile;
  }
  async getPickerResult(context: Context, pickerProfile: picker.PickerProfile): Promise<picker.PickerResult> {
    let result: picker.PickerResult =
      await picker.pick(context, [picker.PickerMediaType.PHOTO, picker.PickerMediaType.VIDEO],
        pickerProfile);
    console.info(`picker resultCode: ${result.resultCode},resultUri: ${result.resultUri},mediaType: ${result.mediaType}`);
    return result;
  }
  getContext(): Context | undefined {
    let uiContext: UIContext = this.getUIContext();
    let context: Context | undefined = uiContext.getHostContext();
    return context;
  }
  build() {
    RelativeContainer() {
      Column() {
        Image(this.imgSrc).width(200).height(200).backgroundColor(Color.Black).margin(5);
        Video({ src: this.videoSrc}).width(200).height(200).autoPlay(true);
        Button("Test Picker Photo&Video").fontSize(20)
          .fontWeight(FontWeight.Bold)
          .onClick(async () => {
            let context = this.getContext();
            if (context === undefined) {
              return;
            }
            let pickerProfile = this.createPickerProfile(context);
            let result = await this.getPickerResult(context, pickerProfile);
            if (result.resultCode == 0) {
              if (result.mediaType === picker.PickerMediaType.PHOTO) {
                this.imgSrc = result.resultUri;
              } else {
                this.videoSrc = result.resultUri;
              }
            }
          }).margin(5);
      }.alignRules({
        center: { anchor: '__container__', align: VerticalAlign.Center },
        middle: { anchor: '__container__', align: HorizontalAlign.Center }
      });
    }
    .height('100%')
    .width('100%')
  }
}

更多关于HarmonyOS 鸿蒙Next模拟器使用camera kit拉起相机拍照的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


鸿蒙Next模拟器通过Camera Kit调用相机拍照,需在module.json5配置相机权限ohos.permission.CAMERA。使用CameraKit类初始化相机实例,通过createCameraInput()创建输入流,调用getPhotoOutput()获取拍照输出能力。执行capture()方法触发拍照,照片将保存至指定沙箱路径。需注意模拟器环境需启用虚拟摄像头功能,并通过getSupportedSizes()校验分辨率支持。

在HarmonyOS Next模拟器中使用Camera Kit拉起相机拍照,可以通过以下步骤实现:

  1. 配置权限:在module.json5文件中添加相机权限:

    "requestPermissions": [
      {
        "name": "ohos.permission.CAMERA"
      }
    ]
    
  2. 导入Camera Kit:在代码中引入相关模块:

    import camera from '[@ohos](/user/ohos).multimedia.camera';
    import { BusinessError } from '[@ohos](/user/ohos).base';
    
  3. 初始化相机:通过camera.getCameraManager获取相机管理器,并调用getSupportedCameras选择可用相机设备。

  4. 创建拍照会话:使用createCaptureSession建立会话,并配置输出流(例如预览流和拍照流)。

  5. 拍照并保存:调用capture方法触发拍照,通过image.Receiver接收图像数据,并使用[@ohos](/user/ohos).multimedia.image[@ohos](/user/ohos).file.fs接口保存为文件。

示例代码片段:

// 创建拍照输出流
const photoOutput: camera.PhotoOutput = ...; // 通过会话创建
photoOutput.capture((err: BusinessError) => {
  if (!err) {
    console.info('Capture started successfully.');
  }
});

注意确保模拟器版本支持Camera Kit功能,并在真机测试时补充动态权限申请。具体实现可参考官方示例:Camera Kit开发指南

回到顶部