HarmonyOS鸿蒙Next中如何使用photoAccessHelper从相册选择图片?

HarmonyOS鸿蒙Next中如何使用photoAccessHelper从相册选择图片? 我需要让用户从相册选择图片,photoAccessHelper 如何使用?如何获取选中图片的 URI?

3 回复

实现思路:

  1. 使用 photoAccessHelper.PhotoViewPicker 创建选择器:
import { photoAccessHelper } from '@kit.MediaLibraryKit';

const picker = new photoAccessHelper.PhotoViewPicker();
  1. 配置选择参数并调用 select:
const result = await picker.select({
  MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
  maxSelectNumber: 9
});
  1. 从结果获取选中图片的 URI 数组:
if (result && result.photoUris.length > 0) {
  this.selectedImages = result.photoUris;
}
  1. 完整示例代码:
import { photoAccessHelper } from '@kit.MediaLibraryKit';

@Entry
@Component
struct PhotoPickerPage {
  @State selectedImages: string[] = [];

  async selectPhotos() {
    try {
      const picker = new photoAccessHelper.PhotoViewPicker();
      const result = await picker.select({
        MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
        maxSelectNumber: 9
      });

      if (result && result.photoUris.length > 0) {
        this.selectedImages = result.photoUris;
        console.info(`Selected ${this.selectedImages.length} photos`);
      }
    } catch (err) {
      console.error(`Select photos failed: ${JSON.stringify(err)}`);
    }
  }

  build() {
    Column({ space: 16 }) {
      Text('相册选择').fontSize(20).fontWeight(FontWeight.Bold)

      Button(`选择图片 (已选${this.selectedImages.length}张)`)
        .onClick(() => this.selectPhotos())

      // 图片网格展示
      if (this.selectedImages.length > 0) {
        Grid() {
          ForEach(this.selectedImages, (uri: string, index: number) => {
            GridItem() {
              Stack() {
                Image(uri)
                  .width('100%')
                  .height('100%')
                  .objectFit(ImageFit.Cover)
                  .borderRadius(4)

                // 删除按钮
                Text('×')
                  .fontSize(16)
                  .fontColor(Color.White)
                  .backgroundColor('rgba(0,0,0,0.5)')
                  .width(24)
                  .height(24)
                  .textAlign(TextAlign.Center)
                  .borderRadius(12)
                  .position({ x: '80%', y: 4 })
                  .onClick(() => {
                    this.selectedImages = this.selectedImages.filter((_, i) => i !== index);
                  })
              }
            }
            .width('100%')
            .aspectRatio(1)
          })
        }
        .columnsTemplate('1fr 1fr 1fr')
        .columnsGap(8)
        .rowsGap(8)
        .width('100%')
        .padding(8)
      }
    }
    .width('100%')
    .padding(16)
  }
}

更多关于HarmonyOS鸿蒙Next中如何使用photoAccessHelper从相册选择图片?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,使用photoAccessHelper从相册选择图片,主要步骤如下:

  1. module.json5文件中请求ohos.permission.READ_IMAGEVIDEO权限。
  2. 导入@kit.MediaLibraryKit模块。
  3. 使用photoAccessHelper.getPhotoAccessHelper(context)获取helper实例。
  4. 通过PhotoSelectOptions设置选择条件(如文件类型、最大选择数)。
  5. 调用photoViewPicker.select(selectOptions)启动选择器并返回所选图片的URI列表。

核心是配置权限、创建选择选项并调用选择器接口。

在HarmonyOS Next中,使用photoAccessHelper从相册选择图片并获取URI,核心步骤如下:

  1. 配置权限:在module.json5中声明ohos.permission.READ_IMAGEVIDEO权限。

  2. 初始化选择器:通过photoAccessHelper.getPhotoAccessHelper()获取helper实例,调用createSelect()方法创建图片选择器。

  3. 配置选择参数:使用PhotoSelectOptions设置选择条件,如:

    • maxSelectNumber:最大选择数量
    • MIMEType:文件类型(如图像/视频)
    • resourceType:资源类型(photoAccessHelper.ResourceType.IMAGE
  4. 启动选择器:调用select()方法启动系统相册界面,该方法返回一个Promise,解析后得到PhotoSelectResult对象。

  5. 获取URI:从PhotoSelectResult.photoUris数组中即可获取选中图片的URI列表。示例:

    const uri = photoSelectResult.photoUris[0];
    

完整示例代码结构:

import photoAccessHelper from '@ohos.file.photoAccessHelper';

// 创建选择器并启动
let photoPicker = photoAccessHelper.getPhotoAccessHelper(context);
let options = {
  maxSelectNumber: 1,
  resourceType: photoAccessHelper.ResourceType.IMAGE
};
photoPicker.select(options).then((result) => {
  console.log('Selected URI:', result.photoUris[0]);
}).catch((err) => {
  console.error('Failed to select photo:', err);
});

注意:需在UIAbility的Context中调用,确保权限弹窗正常触发。

回到顶部