arkts选择照片

发布于 16 天前 未分类 最后更新于 16 天前


封装照片选择方法

    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);

                // 返回选中的图片URI数组
                return result.photoUris;
            } catch (error) {
                throw new Error(error);
            }
        }
    }

调用

    import { ImagePickerUtil } from "../utils/ImagePicker";
    ImagePickerUtil.selectImages(30)
            .then(uris => {
            this.imageList = uris
            })
            .catch((error: BusinessError) => {
            console.error('图片选择异常:', error);
            });

获取图片元数据

通过PhotoViewPicker获取到的照片是一个临时文件,无法获取照片的元数据,需要使用fs.open获取文件的fd再进行操作

    import { fileIo as fs } from '@kit.CoreFileKit';

    const file = fs.openSync(image, fs.OpenMode.READ_ONLY)

    const stat = fs.statSync(file.fd);