arkts使用picker选择相册图片

325 阅读1分钟

介绍

@ohos.file.picker (选择器)

说明:

该模块接口从API version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。

选择器(Picker)是一个封装PhotoViewPicker、DocumentViewPicker、AudioViewPicker等API模块,具有选择与保存的能力。应用可以自行选择使用哪种API实现文件选择和文件保存的功能。该类接口,需要应用在界面UIAbility中调用,否则无法拉起photoPicker应用或FilePicker应用。

导包

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

测试代码

try {
  let PhotoSelectOptions = new picker.PhotoSelectOptions();
  PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
  PhotoSelectOptions.maxSelectNumber = 5;
  let photoPicker = new picker.PhotoViewPicker();
  photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: picker.PhotoSelectResult) => {
    console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
    this.img=PhotoSelectResult.photoUris[0]
  }).catch((err: BusinessError) => {
    console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err));
  });
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err));
}

测试页面

从相册中选择一张图片,并获取uri显示在屏幕之中。

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


@Entry
@Component
struct PickerPage {
  @State message: string = 'picker';
  @State img:string=''
  private example01() {
  try {
    let PhotoSelectOptions = new picker.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
    PhotoSelectOptions.maxSelectNumber = 5;
    let photoPicker = new picker.PhotoViewPicker();
    photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: picker.PhotoSelectResult) => {
      console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
      this.img=PhotoSelectResult.photoUris[0]
    }).catch((err: BusinessError) => {
      console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err));
    });
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err));
  }
}

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            this.example01()
          })
        if(this.img!='')
        Image(this.img).width('50%')
      }
      .width('100%')
    }
    .height('100%')
  }
}

image.png

image.png

image.png