HarmonyOS鸿蒙Next中如何使用imagePicker选择并预览图片?

HarmonyOS鸿蒙Next中如何使用imagePicker选择并预览图片? 如何调用系统相册选择图片并在Image组件中显示?

3 回复

使用@ohos.file.picker模块。需注意PhotoViewPicker返回的是临时URI,可直接赋值给Image。 示例代码

import picker from '@ohos.file.picker';
import { BusinessError } from '@ohos.base';

/**
 * @author J.query
 * @date 2025/12/22 22:07
 * @email j-query@foxmail.com
 * Description:
 */


@Entry
@Component
struct ImagePickerDemo {
  @State imageSrc: string = ''

  build() {
    Column() {
      // 显示图片
      if (this.imageSrc) {
        Image(this.imageSrc)
          .width(200)
          .height(200)
          .objectFit(ImageFit.Cover)
      }
      Button('选择图片')
        .onClick(() => this.selectImage())
        .margin(20)
    }.width('100%').height('100%').justifyContent(FlexAlign.Center)
  }

  async selectImage() {
    try {
      let photoSelectOptions = new picker.PhotoSelectOptions();
      photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
      photoSelectOptions.maxSelectNumber = 1;

      let photoPicker = new picker.PhotoViewPicker();
      let photoSelectResult = await photoPicker.select(photoSelectOptions);

      if (photoSelectResult && photoSelectResult.photoUris && photoSelectResult.photoUris.length > 0) {
        // 取第一个图片的URI
        this.imageSrc = photoSelectResult.photoUris[0];
      }
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`Failed to select image: Code is ${err.code}, message is ${err.message}`);
    }
  }
}

效果:点击按钮拉起相册,选中后图片显示在上方。

cke_1528.png

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


在HarmonyOS Next中,使用@ohos.file.picker模块的PhotoViewPicker选择图片。调用select()方法启动选择器,通过PhotoSelectOptions配置选择参数(如选择数量)。返回的PhotoSelectResult对象包含所选图片的URI列表。使用<Image>组件并设置src为图片URI即可预览。注意申请ohos.permission.READ_IMAGEVIDEO权限。

在HarmonyOS Next中,可以通过PhotoViewPicker来实现系统相册图片选择与预览。以下是核心步骤:

  1. 导入模块

    import picker from '[@ohos](/user/ohos).file.picker';
    import common from '[@ohos](/user/ohos).app.ability.common';
    
  2. 创建选择器并调用

    // 获取UIAbility上下文
    let context = getContext(this) as common.UIAbilityContext;
    
    // 创建图片选择器实例
    let photoPicker = new picker.PhotoViewPicker();
    
    // 调用选择器打开系统相册
    photoPicker.select()
      .then((photoSelectResult: picker.PhotoSelectResult) => {
        // 处理选择的图片
        let uri = photoSelectResult.photoUris[0];
        // 将uri传递给Image组件显示
        this.selectedImageUri = uri;
      })
      .catch((err: Error) => {
        console.error('选择图片失败:', err);
      });
    
  3. Image组件绑定显示

    // 在ArkUI的Image组件中绑定uri
    Image(this.selectedImageUri)
      .width(200)
      .height(200)
    

关键说明

  • 需要申请ohos.permission.READ_IMAGEVIDEO权限
  • 返回的photoUris是数组,支持多选(可通过PhotoViewPickerselect方法配置)
  • 使用PhotoViewPicker而非ImagePicker,这是HarmonyOS Next的API更新

这种方式直接调用系统相册界面,选择后返回图片URI供应用内显示。

回到顶部