本文最后更新于 2025-04-18T20:03:05+08:00
使用photoAccessHelper
相册管理器获取照片
封装照片选择方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import { photoAccessHelper } from '@kit.MediaLibraryKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { dataSharePredicates } from '@kit.ArkData'; import { abilityAccessCtrl } from '@kit.AbilityKit';
export class ImagePickerUtil { static async selectImages(maxSelectNumber: number = 9): Promise<string[]> { try { const options = new photoAccessHelper.PhotoSelectOptions(); options.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; options.maxSelectNumber = maxSelectNumber;
const picker = new photoAccessHelper.PhotoViewPicker();
const result = await picker.select(options);
return result.photoUris; } catch (error) { throw new Error(error); } } }
|
调用
1 2 3 4 5 6 7 8
| import { ImagePickerUtil } from "../utils/ImagePicker"; ImagePickerUtil.selectImages(30) .then(uris => { this.imageList = uris }) .catch((error: BusinessError) => { console.error('图片选择异常:', error); });
|
获取图片元数据
通过PhotoViewPicker
获取到的照片是一个临时文件,无法获取照片的元数据,需要使用fs.open
获取文件的fd再进行操作
1 2 3 4 5
| import { fileIo as fs } from '@kit.CoreFileKit';
const file = fs.openSync(image, fs.OpenMode.READ_ONLY)
const stat = fs.statSync(file.fd);
|