• Lv0
    粉丝0

积分186 / 贡献0

提问33答案被采纳3文章0

如何直接调起图片库 精华

hyacinth养花人

沙发 发表于 2023-10-9 15:06:44

如何直接调起图片库

1.在module.json5配置文件中配置媒体读写权限ohos.permission.READ_MEDIA和ohos.permission.WRITE_MEDIA。

{
  "module" : {
    "requestPermissions":[
      {
        "name" : "ohos.permission.READ\_MEDIA",
        "reason": "\$string:reason"
      },
      {
        "name" : "ohos.permission.WRITE\_MEDIA",
        "reason": "\$string:reason"
      }
    ]
  }
}

2.这两个权限的授权方式均为user_grant,因此需要调用requestPermissionsFromUser接口,以动态弹窗的方式向用户申请授权。

let context = getContext(this) as common.UIAbilityContext;
let atManager = abilityAccessCtrl.createAtManager();
let permissions: Array<string> = ['ohos.permission.READ\_MEDIA','ohos.permission.WRITE\_MEDIA']
atManager.requestPermissionsFromUser(context, permissions)
.then((data) => {
    console.log("Succeed to request permission from user with data: " + JSON.stringify(data))
}).catch((error) => {
    console.log("Failed to request permission from user with error: " + JSON.stringify(error))
})

鲁丙辉

板凳 发表于 2023-12-8 17:58:24

如何直接调起图片库

api9可以使用picker这个api来实现选择图片/文件等; 选择图片的案例如下:

定义选择图片的方法:


export async function fileSelect(): Promise<string> {
  let photoSelectOptions = new picker.PhotoSelectOptions();
  photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
  photoSelectOptions.maxSelectNumber = 1;
  let photoPicker = new picker.PhotoViewPicker();
  try {
    let photoSelectResult = await photoPicker.select(photoSelectOptions);
    if (photoSelectResult && photoSelectResult.photoUris && photoSelectResult.photoUris.length > 0) {
      let imgUri = photoSelectResult.photoUris[0];
      if (imgUri.indexOf('media/image') < 0) {
         showToast($r('app.string.prompt_select_img'));
         return '';
      }
      return imgUri;
    } else {
      return '';
    }
  } catch (err) {
    Logger.error('SelectedImage failed', JSON.stringify(err));
    return '';
  }
}

使用的时候如下:

@Component
struct Layout {
  @State imageUri: string = '';
  selectImage() {
    fileSelect().then((uri: string) => {
      this.imageUri = uri;
    });
  }

  build() {
    Button().onclick(() => this.selectImage())

    if (this.imageUri) {
      Image()
    }
  }
}

Copyright   ©2023  OpenHarmony开发者论坛  京ICP备2020036654号-3 |技术支持 Discuz!

返回顶部