harmony-utils之PhotoHelper,相册相关工具类

简介: harmony-utils 是一款功能丰富的 HarmonyOS 工具库,助力开发者快速构建鸿蒙应用。其子模块 picker_utils 中的 PhotoHelper 提供了便捷的相册操作功能,涵盖图片视频选择、保存、读取及授权管理等常用场景,简化开发流程,提升开发效率。

harmony-utils之PhotoHelper,相册相关工具类

harmony-utils 简介与说明


harmony-utils 一款功能丰富且极易上手的HarmonyOS工具库,借助众多实用工具类,致力于助力开发者迅速构建鸿蒙应用。其封装的工具涵盖了APP、设备、屏幕、授权、通知、线程间通信、弹框、吐司、生物认证、用户首选项、拍照、相册、扫码、文件、日志,异常捕获、字符、字符串、数字、集合、日期、随机、base64、加密、解密、JSON等一系列的功能和操作,能够满足各种不同的开发需求。
picker_utils 是harmony-utils拆分出来的一个子库,包含PickerUtil、PhotoHelper、ScanUtil。

下载安装
ohpm i @pura/harmony-utils
ohpm i @pura/picker_utils

  //全局初始化方法,在UIAbility的onCreate方法中初始化 AppUtil.init()
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    AppUtil.init(this.context);
  }

API方法与使用


select 通过选择模式拉起photoPicker界面,用户可以选择一个或多个图片/视频
//相册选择图片
PhotoHelper.select().then((result) => {
  let uris = result.photoUris;
  let uriStr = `调用相册,返回uris:\n${uris.join('\n')}`;
}).catch((err: BusinessError) => {
  let str = `调用相册,异常:\n${JSON.stringify(err)}`;
});
selectEasy 通过选择模式拉起photoPicker界面,用户可以选择一个或多个图片/视频
//相册选择图片/视频(多选)
let options: photoAccessHelper.PhotoSelectOptions = {
  MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE,
  maxSelectNumber: 12,
  isPhotoTakingSupported: false,
  isSearchSupported: false,
  isEditSupported: false,
  isOriginalSupported: true
}
PhotoHelper.selectEasy(options).then((uris) => {
  let uriStr = `调用相册,返回uris:\n${uris.join('\n')}`;
}).catch((err: BusinessError) => {
  let str = `调用相册,异常:\n${JSON.stringify(err)}`;
});

//相册选择图片(单选)
let options: photoAccessHelper.PhotoSelectOptions = {
  MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE,
  maxSelectNumber: 1,
  isOriginalSupported: true,
  isPreviewForSingleSelectionSupported: true //单选模式下是否需要进大图预览
}
PhotoHelper.selectEasy(options).then((uris) => {
  let uriStr = `调用相册,返回uris:\n${uris.join('\n')}`;
}).catch((err: BusinessError) => {
  let str = `调用相册,异常:\n${JSON.stringify(err)}`;
});
save 申请权限保存,保存图片或视频到相册
//图片保存进相册(已申请权限使用该方法)
let ps: Permissions[] = ['ohos.permission.WRITE_IMAGEVIDEO'];
PermissionUtil.requestPermissions(ps).then((result) => {
  if (result) {
    let imgName = `漂亮小姐姐_${DateUtil.getTodayTime()}`;
    PhotoHelper.save(photoAccessHelper.PhotoType.IMAGE, 'jpg', { title: imgName }).then(async (uri) => {
      if (uri) {
        let uriStr = `保存图片成功,返回uris:\n${uri}`;
        let file = FileUtil.openSync(uri);
        FileUtil.copyFile(this.filePath, file.fd).then(() => {
          FileUtil.close(file.fd);
          ToastUtil.showToast("图片保存成功");
        })
      }
    }).catch((err: BusinessError) => {
      let str = `调用保存图片,异常:\n${JSON.stringify(err)}`;
    })
  } else {
    ToastUtil.showLong("请在设置中打开权限");
    WantUtil.toAppSetting();
  }
});
showAssetsCreationDialog 弹窗授权保存,调用接口拉起保存确认弹窗
let pixelMap = await ImageUtil.getPixelMapFromMedia($r("app.media.test_as4"));
let filePath = await ImageUtil.savePixelMap(pixelMap, FileUtil.getFilesDirPath(""), "漂亮小姐姐.png");
let uri = FileUtil.getUriFromPath(this.filePath);
let srcFileUris: Array<string>=[uri];

let desFileUris: Array<string> = await PhotoHelper.showAssetsCreationDialog(srcFileUris);
for (let index = 0; index < desFileUris.length; index++) {
  //将来源于应用沙箱的照片内容写入媒体库的目标uri
  let srcFile: fs.File = await Utils.open(srcFileUris[index], fs.OpenMode.READ_ONLY);
  let desFile: fs.File = await Utils.open(desFileUris[index], fs.OpenMode.WRITE_ONLY);
  await Utils.copyFile(srcFile.fd, desFile.fd);
  await Utils.close(srcFile);
  await Utils.close(desFile);
}
showAssetsCreationDialogEasy 弹窗授权保存,调用接口拉起保存确认弹窗,并保存
let pixelMap = await ImageUtil.getPixelMapFromMedia($r("app.media.test_as4"));
let filePath = await ImageUtil.savePixelMap(pixelMap, FileUtil.getFilesDirPath(""), "漂亮小姐姐.png");
let uri = FileUtil.getUriFromPath(this.filePath);

PhotoHelper.showAssetsCreationDialogEasy([uri, uri2]).then((result) => {
  let uriStr = `图片保存成功,返回uris:\n${JSON.stringify(result, null, 2)}`;
  DialogHelper.showToast("图片保存成功!");
}).catch((error: BusinessError) => {
  DialogHelper.showToast("图片保存失败!");
});
applyChanges 安全控件保存,提交媒体变更请求,插入图片/视频
//安全控件保存,图片保存进相册。
let pixelMap = await ImageUtil.getPixelMapFromMedia($r("app.media.test_as4"));
let filePath = await ImageUtil.savePixelMap(pixelMap, FileUtil.getFilesDirPath(""), "漂亮小姐姐.png");

let uri = FileUtil.getUriFromPath(this.filePath);
PhotoHelper.applyChanges(uri).then((result) => {
  let uriStr = `保存图片成功:${result.uri}`;
}).catch((err: BusinessError) => {
  let str = `保存图片失败:${JSON.stringify(err)}`;
});
getPhotoAsset 获取对应uri的PhotoAsset对象,用于读取文件信息
PickerUtil.selectPhoto().then(async (uris) => {
  if (uris && uris.length > 0) {
    PhotoHelper.getPhotoAsset(uris[0]).then((photoAsset) => {
      try {
        let name = photoAsset?.get(photoAccessHelper.PhotoKeys.DISPLAY_NAME);
        let type = photoAsset?.get(photoAccessHelper.PhotoKeys.PHOTO_TYPE);
        let title = photoAsset?.get(photoAccessHelper.PhotoKeys.TITLE.toString());
        let size = photoAsset?.get(photoAccessHelper.PhotoKeys.SIZE.toString());
        let with1 = photoAsset?.get(photoAccessHelper.PhotoKeys.WIDTH.toString());
        let height = photoAsset?.get(photoAccessHelper.PhotoKeys.HEIGHT.toString());
        let date = photoAsset?.get(photoAccessHelper.PhotoKeys.DATE_TAKEN.toString());
        let orientation = photoAsset?.get(photoAccessHelper.PhotoKeys.ORIENTATION.toString());
        let uriStr = `图片信息:\n文件名:${name}\n文件类型:${type}\n文件大小:${size}\n图片宽度:${with1}\n图片高度:${height}\n拍摄日期:${date}\n文件标题:${title}\n图片文件的方向:${orientation}`
      } catch (err) {
        LogUtil.error("读取图片信息失败:" + JSON.stringify(err));
      }
      photoAsset?.getThumbnail((err, pixelMap) => {
        if (err) {
          LogUtil.error("缩略图-异常:" + JSON.stringify(err));
          return;
        }
        // this.pixelMap = pixelMap;
      })
    }).catch((err: BusinessError) => {
      let str = `读取图片异常:\n${JSON.stringify(err)}`;
    });
  } else {
    ToastUtil.showToast("请选择图片");
  }
}).catch((err: BusinessError) => {
  let str = `异常:\n${JSON.stringify(err)}`;
});

创作不易,请给童长老点赞👍


https://github.com/787107497/harmony-utils
https://gitee.com/tongyuyan/harmony-utils
OpenHarmony三方库

目录
相关文章
|
开发工具 Android开发 iOS开发
2023年APP备案操作教程 阿里云APP备案试列 APP公钥sha1签名获取方法
核心要点:A,域名之前是哪里备案的,APP备案就到哪里去做,方便简单;B,APP备案核心预存信息为APP包名、MD5指纹(安卓)、sha1签名(IOS)、公钥;这3个信息请找APP开发人员获取;一门开发的可以自行到开发者后台【配置】-【证书与包名】获取对应安卓、苹果APP信息。
|
存储 程序员 编译器
|
关系型数据库 PostgreSQL Docker
harbor-db重启报错:initdb: error: directory "/var/lib/postgresql/da..
harbor-db重启报错:initdb: error: directory "/var/lib/postgresql/da..
1166 1
|
5月前
|
Ubuntu 关系型数据库 Docker
Docker 跑 Memos 镜像:私有 Markdown 笔记部署实测记录
Memos 是一款开源、可自托管的轻量笔记工具:镜像仅约20MB,SQLite默认存储,一条 `docker run` 即可启动;浏览器写Markdown、打#标签、按时间线浏览,手机电脑同步,数据完全掌握在自己服务器上。
629 0
Docker 跑 Memos 镜像:私有 Markdown 笔记部署实测记录
|
6月前
|
前端开发 开发者 容器
前端组件库 ——LayUI 知识点大全(二)
教程来源 https://tmywi.cn LayUI提供灵活的布局系统,含固定宽(layui-container)与自适应宽(layui-fluid)两种容器;栅格基于12列响应式设计,支持多端适配(xs/sm/md/lg)、列偏移、列间距等功能,助力快速构建现代化页面结构。
|
9月前
|
存储 缓存 监控
婚恋交友系统开发解决方案:基于TP6框架的多端同步平台搭建实战
本项目是基于ThinkPHP6与Uni-App开发的多端婚恋社交小程序,支持微信/APP/PC三端同步。集成实名/学历/收入多级认证、媒婆推广、门店加盟、WebRTC音视频房间、混合匹配算法及LBS活动系统,具备会员订阅、虚拟礼物、红娘服务等多元盈利模式,架构稳定、安全可靠、易于扩展。
775 1
婚恋交友系统开发解决方案:基于TP6框架的多端同步平台搭建实战
|
8月前
|
测试技术 微服务
Cookie之domain
本以为我对cookie这个小玩具已经很了解, 后来才发现,只是皮毛罢了,还需要继续学。
759 1
|
10月前
|
数据采集 人工智能 物联网
教AI学会说'我是小喵'竟然这么神奇?LlamaFactory微调揭秘
想让AI助手记住自己叫什么名字?就像教小孩背诵身份证信息一样简单!通过LlamaFactory的SFT微调,你的AI不仅能记住自己是谁,还能在千万个问题中准确回答身份信息。从技术小白到微调高手,一篇文章搞定! #人工智能 #LlamaFactory #模型微调 #AI助手
757 2
|
10月前
|
Devops 开发工具 git
【架构基础】互联网大厂Git多分支规范
Git分支管理是通过创建多分支实现并行开发、代码隔离与版本控制的协作模式。以master和develop为核心,结合feature、release、hotfix等分支,规范开发流程,提升团队协作效率与代码质量。
1483 0
|
11月前
|
消息中间件 人工智能 Linux
基于 RocketMQ 构建 高可靠 A2A 通信通道
A2A协议由Google于2025年发起,旨在构建跨厂商AI智能体的标准化通信机制。通过支持gRPC、JSON-RPC及RocketMQ异步通信,实现多智能体高效协同。基于RocketMQ的实现方案提供开箱即用的高可靠通信,支持任务分发、流式交互与状态查询,助力构建开放、可扩展的多智能体系统生态。(238字)

热门文章

最新文章