HarmonyOS鸿蒙Next中如何使用cameraPicker拍照并获取图片?

HarmonyOS鸿蒙Next中如何使用cameraPicker拍照并获取图片? 我需要调用系统相机拍照,如何使用 cameraPicker?如何获取拍摄的图片并显示?

3 回复

实现思路:

  1. 使用 cameraPicker.pick 调用系统相机:
import { cameraPicker } from '@kit.CameraKit';

const result = await cameraPicker.pick(context, [cameraPicker.PickerMediaType.PHOTO], {
  cameraPosition: cameraPicker.CameraPosition.BACK
});
  1. 从返回结果获取图片 URI:
if (result && result.resultUri) {
  this.imageUri = result.resultUri;
}
  1. 使用 Image 组件显示拍摄的图片:
Image(this.imageUri)
  .width('100%')
  .height(300)
  1. 完整示例代码:
import { cameraPicker } from '@kit.CameraKit';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct CameraPickerPage {
  @State imageUri: string = '';
  @State hasImage: boolean = false;
  private context = getContext(this) as common.UIAbilityContext;

  async takePhoto() {
    try {
      const result = await cameraPicker.pick(this.context, 
        [cameraPicker.PickerMediaType.PHOTO], 
        {
          cameraPosition: cameraPicker.CameraPosition.BACK
        }
      );

      if (result && result.resultUri) {
        this.imageUri = result.resultUri;
        this.hasImage = true;
        console.info(`Photo taken: ${this.imageUri}`);
      }
    } catch (err) {
      console.error(`Take photo failed: ${JSON.stringify(err)}`);
    }
  }

  build() {
    Column({ space: 20 }) {
      Text('相机拍照').fontSize(20).fontWeight(FontWeight.Bold)

      // 图片预览区域
      if (this.hasImage) {
        Image(this.imageUri)
          .width('100%')
          .height(300)
          .objectFit(ImageFit.Contain)
          .borderRadius(8)
      } else {
        Column() {
          Text('暂无图片').fontSize(16).fontColor('#999')
        }
        .width('100%')
        .height(300)
        .backgroundColor('#F5F5F5')
        .borderRadius(8)
        .justifyContent(FlexAlign.Center)
      }

      // 操作按钮
      Row({ space: 20 }) {
        Button('拍照')
          .onClick(() => this.takePhoto())

        if (this.hasImage) {
          Button('清除')
            .backgroundColor('#FF4444')
            .onClick(() => {
              this.imageUri = '';
              this.hasImage = false;
            })
        }
      }
    }
    .width('100%')
    .padding(20)
  }
}

更多关于HarmonyOS鸿蒙Next中如何使用cameraPicker拍照并获取图片?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,使用@ohos.file.picker模块的PhotoViewPicker实现拍照并获取图片。首先导入模块,创建PhotoViewPicker实例,通过select方法调用相机。在PhotoSelectOptions中设置MIMETypeimage/*selectModephoto。成功后会返回PhotoSelectResult,其中包含所选图片的URI数组,可通过fs模块读取文件数据。

在HarmonyOS Next中,使用cameraPicker拍照并获取图片的流程如下:

  1. 导入模块
import picker from '@ohos.file.picker';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
  1. 创建并启动拍照选择器
async function takePhoto(context: common.Context) {
  try {
    const photoPicker = new picker.PhotoViewPicker();
    const result = await photoPicker.select({
      pickerMode: picker.PhotoViewPicker.PickerMode.IMAGE, // 选择图片模式
      maxSelectNumber: 1 // 最多选择1张
    });
    
    if (result && result.photoUris && result.photoUris.length > 0) {
      const uri = result.photoUris[0];
      // 处理获取的图片URI
      await processImage(uri);
    }
  } catch (err) {
    console.error('拍照失败:', err);
  }
}
  1. 处理图片并显示
async function processImage(uri: string) {
  try {
    // 方案1:直接使用URI显示(适用于Image组件)
    // 在ArkUI中:Image(uri).width(100).height(100)
    
    // 方案2:读取文件内容
    const file = await fs.open(uri, fs.OpenMode.READ_ONLY);
    const stat = await fs.stat(file.fd);
    const buffer = new ArrayBuffer(stat.size);
    await fs.read(file.fd, buffer);
    await fs.close(file.fd);
    
    // 可将buffer转换为base64或用于其他处理
    // const base64 = arrayBufferToBase64(buffer);
    
  } catch (err) {
    console.error('处理图片失败:', err);
  }
}

// ArrayBuffer转base64辅助函数
function arrayBufferToBase64(buffer: ArrayBuffer): string {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  for (let i = 0; i < bytes.byteLength; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary);
}
  1. 权限配置(在module.json5中):
{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.READ_IMAGEVIDEO",
        "reason": "$string:reason"
      }
    ]
  }
}

关键点说明

  • PhotoViewPicker默认会调用系统相机拍照
  • 返回的photoUris是临时文件URI,应用关闭后可能失效
  • 如需永久保存,需将文件复制到应用目录
  • 显示图片时,Image组件可直接使用返回的URI

这种方式通过系统选择器调用相机,符合HarmonyOS Next的安全规范,无需直接申请相机权限。

回到顶部