参考示例:import photoAccessHelper from '@ohos.file.photoAccessHelper'; import image from '@ohos.multimedia.image'; import fs from '@ohos.file.fs'; import { buffer } from '@kit.ArkTS'; @Entry @Component struct Page2 { @State resultBase64Str: string = ''; @State getAlbum: string = '显示相册中的图片'; @State pixel: image.PixelMap | undefined = undefined; @State albumPath: string = ''; @State photoSize: number = 0; async getPictureFromAlbum() { // 拉起相册,选择图片 let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions(); PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; PhotoSelectOptions.maxSelectNumber = 1; let photoPicker = new photoAccessHelper.PhotoViewPicker(); let photoSelectResult: photoAccessHelper.PhotoSelectResult = await photoPicker.select(PhotoSelectOptions); this.albumPath = photoSelectResult.photoUris[0]; console.info('albumPath: ' + this.albumPath) // 读取图片为buffer const file = fs.openSync(this.albumPath, fs.OpenMode.READ_WRITE); this.photoSize = fs.statSync(file.fd).size; console.info('Photo Size: ' + this.photoSize); let buffer1 = new ArrayBuffer(this.photoSize); fs.readSync(file.fd, buffer1); let base64Str: string = buffer.from(buffer1).toString('base64') let resultBase64Str = "data:image/png;base64," + base64Str this.resultBase64Str = resultBase64Str fs.closeSync(file); // 解码成PixelMap const imageSource = image.createImageSource(buffer1); console.log('imageSource: ' + JSON.stringify(imageSource)); this.pixel = await imageSource.createPixelMap({}); } build() { Scroll() { Column() { Text('获取图片') .onClick(async () => { await this.getPictureFromAlbum() }) // Image(this.pixel) Image(this.resultBase64Str).width(40).height(40) Text(this.resultBase64Str) } } } }
参考示例: