文档管理中心
FAQ媒体开发拍照和图片图片处理(Image)如何读取相册中的图片

如何读取相册中的图片

使用photoAccessHelper.PhotoSelectOptions接口读取相册中的图片

收起
自动换行
深色代码主题
复制
  1. import { photoAccessHelper } from '@kit.MediaLibraryKit';
  2. import { image } from '@kit.ImageKit';
  3. import { fileIo } from '@kit.CoreFileKit';
  4. @Entry
  5. @Component
  6. struct Index {
  7. @State getAlbum: string = '显示相册中的图片';
  8. @State pixel: image.PixelMap | undefined = undefined;
  9. @State albumPath: string = '';
  10. @State photoSize: number = 0;
  11. async getPictureFromAlbum() {
  12. // Pull up the album and select the pictures
  13. let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
  14. PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
  15. PhotoSelectOptions.maxSelectNumber = 1;
  16. let photoPicker = new photoAccessHelper.PhotoViewPicker();
  17. let photoSelectResult: photoAccessHelper.PhotoSelectResult = await photoPicker.select(PhotoSelectOptions);
  18. this.albumPath = photoSelectResult.photoUris[0];
  19. // Read the image as a buffer
  20. const file = fileIo.openSync(this.albumPath, fileIo.OpenMode.READ_ONLY);
  21. this.photoSize = fileIo.statSync(file.fd).size;
  22. console.info('Photo Size: ' + this.photoSize);
  23. let buffer = new ArrayBuffer(this.photoSize);
  24. fileIo.readSync(file.fd, buffer);
  25. fileIo.closeSync(file);
  26. // Decoding into PixelMap
  27. const imageSource = image.createImageSource(buffer);
  28. console.log('imageSource: ' + JSON.stringify(imageSource));
  29. this.pixel = await imageSource.createPixelMap({});
  30. }
  31. build() {
  32. Row() {
  33. Column() {
  34. Image(this.pixel)
  35. .width('100%')
  36. .aspectRatio(1)
  37. Button('显示照片')
  38. .onClick(() => {
  39. this.getPictureFromAlbum();
  40. })
  41. }
  42. .width('100%')
  43. }
  44. .height('100%')
  45. }
  46. }
在 FAQ 中进行搜索
请输入您想要搜索的关键词