当前位置: 首页 > news >正文

鸿蒙下载图片保存到相册,截取某个组件保存到相册

鸿蒙下载图片保存到相册,截取某个组件保存到相册

import { image } from '@kit.ImageKit'
import photoAccessHelper from '@ohos.file.photoAccessHelper'
import { BusinessError } from '@kit.BasicServicesKit'
import { http } from '@kit.NetworkKit'
import fs from '@ohos.file.fs';
import { fileUri } from '@kit.CoreFileKit';
import { Context, Permissions } from '@kit.AbilityKit';
import { componentSnapshot } from '@kit.ArkUI';
import { PermissionUtil } from '../util/PermissionUtil';
import { PhotoHelper } from '../util/PhotoHelper';
import { FileUtil } from '../util/FileUtil';
import { LogUtil } from '@ohos/commonlibrary';//保存画报到相册
function savePictorialToPhoto() {//TODO:let pixmap: image.PixelMap | undefined = undefinedlet uriStr: string = ''//截图,“root”是组件的idlet pixelmap = componentSnapshot.getSync("root", { scale: 2, waitUntilRenderFinished: true })pixmap = pixelmapconsole.log("测试保存"+JSON.stringify(pixmap))//保存本地-相册//Dialog截图let ps: Permissions[] = ['ohos.permission.WRITE_IMAGEVIDEO'];PermissionUtil.requestPermissions(ps).then((result) => {if (result) {LogUtil.debug("测试保存"+result)let imgName = `海报_${new Date().getTime()}`;PhotoHelper.save(photoAccessHelper.PhotoType.IMAGE, 'png', { title: imgName }).then(async (uri) => {if (uri) {uriStr = `调用2保存图片,返回uris:\n${uri}`let file = FileUtil.openSync(uri);let packOpts: image.PackingOption = { format: 'image/png', quality: 100 }PhotoHelper.packToFileFromPixelMap(pixmap!!, file.fd, packOpts).then(() => {FileUtil.close(file.fd);console.log("测试保存成功")})}}).catch((err: BusinessError) => {uriStr = `调用保存图片,异常:\n${JSON.stringify(err)}`})} else {console.log("测试保存失败")}})
}@Entry
@Component/***首页*/
struct CeshiPage {build() {//底部导航栏Column() {Button('测试保存相册').onClick(() => {this.dowImageAndSave("http://img14.360buyimg.com/imgzone/jfs/t1/317716/18/12967/150513/686749d5Fef9f99f1/eeefe1ff7bce6117.png",getContext())})Button('测试截图保存相册').onClick(() => {savePictorialToPhoto()})}.id("root").width('100%').height('100%')}async dowImageAndSave(url: string, context: Context) {let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context)let pixelMap: PixelMap | undefined = undefinedlet packOptions: image.PackingOption = { format: 'image/jpeg', quality: 98 }let imagePackerApi = image.createImagePacker()// 下载图片到本地http.createHttp().request(url, {method: http.RequestMethod.GET,connectTimeout: 60000,readTimeout: 60000}, async (error: BusinessError, data: http.HttpResponse) => {if (error) {console.log(`${error.code},${error.message}`)} else {let imageData: ArrayBuffer = data.result as ArrayBufferlet ImageSource: image.ImageSource = image.createImageSource(imageData)//   创建pixelmap对象pixelMap = await ImageSource.createPixelMap()const path: string = context.cacheDir + "/save_image.jpg"//   写入本地let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)await imagePackerApi.packToFile(pixelMap, file.fd, packOptions)// 获取图片urilet uri = fileUri.getUriFromPath(path)//   复制图片到相册let uris: Array<string> = [uri]let photoCreationConfig: Array<photoAccessHelper.PhotoCreationConfig> = [{title: 'dowImg',fileNameExtension: 'jpg',photoType: photoAccessHelper.PhotoType.IMAGE,subtype: photoAccessHelper.PhotoSubtype.DEFAULT}]//   基于弹窗授权的方式获取媒体库的目标urilet desFileuris: Array<string> = await phAccessHelper.showAssetsCreationDialog(uris, photoCreationConfig)//   将应用沙箱的照片写入媒体库let desFile: fs.File = await fs.open(desFileuris[0], fs.OpenMode.WRITE_ONLY) //  相册let srcFile: fs.File = await fs.open(uri, fs.OpenMode.READ_ONLY) // 沙箱图片// 沙箱图片复制到相册await fs.copyFile(srcFile.fd, desFile.fd).then(() => {fs.close(srcFile)fs.close(desFile)})}})//=====================}
}
http://www.dtcms.com/a/327890.html

相关文章:

  • 农业园区气象站在高标准农田的用处
  • 行业热点丨智能仿真时代:电子工程多物理场解决方案创新实践
  • USLR:一款用于脑MRI无偏倚平滑纵向配准的开源工具|文献速递-医学影像算法文献分享
  • 体育数据api接口,足球api篮球api电竞api,比赛赛事数据api
  • vmware虚拟机Ubuntu系统奔溃修复
  • 西安国际数字科创产业园:政策赋能筑长安数字产业集群
  • Linux学习-软件编程(标准IO)
  • 【ROS2】ROS2 基础学习教程 以lerobot-so100为例
  • specCPU2017在麒麟系统的简单测试
  • VisionPro——1.VP与C#联合
  • 前端/在vscode中创建Vue3项目
  • 【实时Linux实战系列】实时环境监测系统架构设计
  • 多奥电梯智能化解决方案的深度解读与结构化总结,内容涵盖系统架构、功能模块、应用场景与社会价值四大维度,力求全面展示该方案的技术先进性与应用前景。
  • HTTPS服务
  • 重构与性能的平衡术:先优化结构,再优化速度
  • 机器学习—— TF-IDF文本特征提取评估权重 + Jieba 库进行分词(以《红楼梦》为例)
  • A1-MPLS-LDP配置
  • 【MongoDB】简单理解聚合操作,案例解析
  • MongoDB分析insert源代码
  • Android init.rc详解
  • 【Linux】init和bash的区别
  • CentOS 7.9 升级 GLibc 2.34
  • secureCRT ymodem协议连续传输文件速率下降
  • C++Linux八股
  • 机器学习 [白板推导](十)[马尔可夫链蒙特卡洛法]
  • 机试备考笔记11/31
  • Elasticsearch JS 自定义 ConnectionPool / Connection / Serializer、敏感信息脱敏与 v8 平滑迁移
  • 数据结构——栈和队列2
  • JAiRouter 0.2.1 更新啦:内存优化 + 配置合并 + IP 限流增强,运维体验再升级
  • TCP/IP、socket、http