HarmonyOS DocumentViewPicker选择文件问题

通过DocumentViewPicker打开文件选择器,选择图库里的图片能够拿到返回的uri,但是无法加载出图片。通过PhotoViewPicker图库选择器来选择同样一张图片返回同样的uri就能正确加载图片。使用这两个选择器之前是否需要申请相关权限?

HarmonyOS
4天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
shlp

参考示例如下:

import photoAccessHelper from '@ohos.file.photoAccessHelper';
import image from '@ohos.multimedia.image';
import fs from '@ohos.file.fs';
import { buffer } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
import picker from '@ohos.file.picker';

@Entry
@Component
struct Page2 {
  @State resultBase64Str: string = '';
  @State pixel: image.PixelMap | undefined = undefined;
  @State albumPath: string = '';
  @State photoSize: number = 0;

  getPhotoUrl() {
    try {
      let uris: Array<string> = [];
      let DocumentSelectOptions = new picker.DocumentSelectOptions();
      let documentPicker = new picker.DocumentViewPicker();
      documentPicker.select(DocumentSelectOptions).then(async (DocumentSelectResult: Array<string>) => {
        console.info('DocumentViewPicker.select successfully, DocumentSelectResult uri: ' +
        JSON.stringify(DocumentSelectResult));
        uris = DocumentSelectResult;
        let uri: string = uris[0];
        console.info('打印 uri:' + uri);
        let file = fs.openSync(uri, fs.OpenMode.READ_ONLY) //通过传入文件描述符来创建图片源实例
        let imageSource: image.ImageSource = image.createImageSource(file.fd);
        this.pixel = await imageSource.createPixelMap();

        let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };
        let imagePackerApi = image.createImagePacker();
        imagePackerApi.packing(this.pixel, packOpts).then((data: ArrayBuffer) => {
          let base64Str = buffer.from(data).toString('base64')
          this.resultBase64Str = "data:image/png;base64," + base64Str
          console.log('resultBase64Str = ', this.resultBase64Str)
        }).catch((error: BusinessError) => {
          console.error('Failed to pack the image. And the error is: ' + error);
        })
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`PhotoViewPicker failed with err: ${err.code}, ${err.message}`);
    }
  }

  build() {
    Scroll() {
      Column() {
        Text('获取图片')
          .onClick(() => {
            this.getPhotoUrl();
          })
        Image(this.pixel)
      }
    }
  }
}
分享
微博
QQ
微信
回复
3天前
相关问题
HarmonyOS 列表选择问题
155浏览 • 1回复 待解决
HarmonyOS 组件选择问题
49浏览 • 1回复 待解决
HarmonyOS 如何实现文件选择功能?
207浏览 • 1回复 待解决
HarmonyOS photoAccessHelper选择图片问题
27浏览 • 1回复 待解决
如何打开指定文件夹,选择文件返回
8950浏览 • 1回复 待解决