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

鸿蒙图片缓存(一)

    移动端开发过程中图片缓存功能是必备,iOS和安卓都有相关工具库,鸿蒙系统组件本身也自带缓存功能,但是遇到复杂得逻辑功能还是需要封装图片缓存工具。

系统组件Image

1. Image的缓存策略

Image模块提供了三级Cache机制,解码后内存图片缓存、解码前数据缓存、物理磁盘缓存。在加载图片时会逐级查找,如果在Cache中找到之前加载过的图片则提前返回对应的结果。

2. Image组件如何配置打开和关闭缓存

  • 内存图片缓存:通过setImageCacheCount接口打开缓存,如果希望每次联网都获取最新资源,可以不设置或设置为0不缓存。
  • 磁盘缓存:磁盘缓存是默认开启的,默认值为100M,可以将setImageFileCacheSize的值设置为0关闭磁盘缓存。
  • 解码前数据缓存:通过setImageRawDataCacheSize设置内存中缓存解码前图片数据的大小上限,单位为字节,提升再次加载同源图片的加载速度。如果不设置则默认为0,不进行缓存
import app, { AppResponse } from '@system.app';@Entry
@Component
struct Home {url: string = '';aboutToAppear(): void {app.setImageCacheCount(6)//内存缓存数量app.setImageRawDataCacheSize(10 * 1024 * 1024)//10Mapp.setImageFileCacheSize(100 * 1024 * 1024) //磁盘缓存 100M}build() {Column() {Image(this.url)}.height('100%').width('100%')}}

鸿蒙官方明确:setImageCacheCount、setImageRawDataCacheSize和setImageFileCacheSize这这三个图片缓存接口灵活性不足,后续不再更新

封装图片缓存库

       由于系统图片缓存不好用,尝试封装图片下载和缓存工具。下载使用多线程taskTool子线程分发下载任务,使用request.downloadFile具体执行下载。内存缓存使用使magLruCache会根据使用图片频率,自动删除使用率低的缓存内存图片。磁盘使用文件存储。

图片获取逻辑

从内存缓存中取图片,如果没有再从磁盘文件中取图片,都没有则开启现在任务下载

 /*** 文件下载并拿到缓存返回给调用者,如果下载和图片解析失败返回链接,通过下载链接进行加载,利用系统缓存机制进行加载。* @param context 上下文* @param downloadUrl 图片地址* @param downloadPath 缓存地址* @returns 返回PixelMap 失败返回downloadUrl*/downloadCachedFile(downloadUrl: string): Promise<image.PixelMap | string> {return new Promise(async (resolve, _) => {try {//1、获取图片类型例如 .png/.jpg/.weep等。//目前不用图片类型,应为图片链接可能无任何类型信息。//2、获取MD5摘要let downloadUrlMd5 = await new Md5Util().doMd(downloadUrl)//3、获取图片文件名称let newImageFileName = this.getImageFileName(downloadUrlMd5)//4、拼接下载路径地址let downloadPath = this.dir + this.separator + newImageFileName//5、检测图片文件夹是否存在,否->创建let existedBefore = FileUtil.checkAndMkdirSync(this.dir)//之前存在才应该去遍历文件,然后更新文件if (existedBefore) {//判断此图片资源是否已经被缓存到了文件夹下面let findFileExistInFolder = await this.findFileNameInFolder(this.dir, downloadUrlMd5)//如果存在去更新文件名称,否则去下载if (findFileExistInFolder[0]) {newImageFileName = await this.renameOfImageByDataTime(findFileExistInFolder[1], newImageFileName)downloadPath = this.dir + this.separator + newImageFileName//加入gif判断获取缓存,名称改变,对应的缓存需要更新到缓存里面let type = await this.getImageType(downloadPath)if (this.GIF_IMAG_TYPES.includes(type)){const gifUri = this.URI_HEAD + downloadPathImageCacheUtil.imagLruCache.put(downloadUrlMd5, gifUri)}//内存中取let mapCachePixMap = ImageCacheUtil.imagLruCache.get(downloadUrlMd5)if (mapCachePixMap) {resolve(mapCachePixMap)return}//磁盘文件中取let pixelMap = await this.uriOrPathConvertPixelMap(downloadPath)if (pixelMap) {ImageCacheUtil.imagLruCache.put(downloadUrlMd5, pixelMap)resolve(pixelMap)return}}}//如果图片文件夹不存在就去下载this.downloadFile(this.context,downloadUrlMd5, downloadUrl, downloadPath).then((resultEnd) => {resolve(resultEnd)return}).catch((_: BusinessError) => {resolve(downloadUrl)return})} catch (err) {console.error(this.TAG + `::downLoadCacheFile error message = ${err.stack?.toString()}`)resolve(downloadUrl)return}})}

request.downloadFile下载图片文件解析成pixMap

 /*** 网络下载图片方法* @param context* @param downloadUrl* @param downloadPath* @returns*/private async downloadFile(context: Context,downloadUrlMd5:string, downloadUrl: string,downloadPath: string): Promise<image.PixelMap | string> {return new Promise(async (resolve, reject) => {//6、检测文件夹大小如果大于200M,就需要删除一半的图片资源this.clearHalfCache(this.dir)request.downloadFile(context, { url: downloadUrl, filePath: downloadPath }).then((downloadTask: request.DownloadTask) => {downloadTask.on('complete', async () => {let type = await this.getImageType(downloadPath)if (this.noCatchImageType.includes(type)) {this.clearImageFailCache(downloadPath)resolve(downloadUrl);return}if (this.GIF_IMAG_TYPES.includes(type)) {const fileUri = this.URI_HEAD + downloadPathImageCacheUtil.imagLruCache.put(downloadUrlMd5, fileUri)resolve(fileUri)return}let catchPixelMap = await this.uriOrPathConvertPixelMap(downloadPath);if (catchPixelMap) {ImageCacheUtil.imagLruCache.put(downloadUrlMd5, catchPixelMap)resolve(catchPixelMap)return}reject(new Error('PixelMap编码失败'));});downloadTask.on('fail', (error) => {console.error(this.TAG + `::downloadFile downloadTask fail error= ${error?.toString()}`)//下载失败需要删除本地路径,然后返回下载缓存路径this.clearImageFailCache(downloadPath);reject(new Error('图片下载失败'));});}).catch((err: BusinessError) => {console.error(`${this.TAG}::downloadFile Failed to request the download. Code: ${err.code}, message: ${err.message}`);this.clearImageFailCache(downloadPath);reject("err message:" + err.message + ",error code:" + err.code)});})}

http://www.lqws.cn/news/176743.html

相关文章:

  • Python读取PDF:文本、图片与文档属性
  • 《从零掌握MIPI CSI-2: 协议精解与FPGA摄像头开发实战》-- CSI-2 协议详细解析 (一)
  • Tika Server:企业级文档内容解析的轻量级服务化方案
  • CppCon 2015 学习:How to Make Your Data Structures Wait-Free for Reads
  • 【iOS安全】iPhone X iOS 16.7.11 (20H360) WinRa1n 越狱教程
  • 主流 AI IDE 之一的 Cursor 介绍
  • 2506,字节对齐
  • 【配置 YOLOX 用于按目录分类的图片数据集】
  • 96. 2017年蓝桥杯省赛 - Excel地址(困难)- 进制转换
  • transformer和 RNN以及他的几个变体区别 改进
  • cnn卷积神经变体
  • 豆包和deepseek 元宝 百度ai区别是什么
  • 大语言模型提示词(LLM Prompt)工程系统性学习指南:从理论基础到实战应用的完整体系
  • 大数据学习(132)-HIve数据分析
  • 【LLMs篇】14:扩散语言模型的理论优势与局限性
  • 海康工业相机文档大小写错误
  • vite配置@别名,以及如何让IDE智能提示路经
  • 亚矩阵云手机实测体验:稳定流畅背后的技术逻辑​
  • RabbitMQ入门4.1.0版本(基于java、SpringBoot操作)
  • Visual Studio 中的 MD、MTD、MDD、MT 选项详解
  • Neo4j 集群管理:原理、技术与最佳实践深度解析
  • MVC与MVP设计模式对比详解
  • ABP VNext 与 Neo4j:构建基于图数据库的高效关系查询
  • Spring Cloud 2025.0.0 Gateway迁移全过程详解
  • 【行驶证识别成表格】批量OCR行驶证识别与Excel自动化处理系统,行驶证扫描件和照片图片识别后保存为Excel表格,基于QT和华为ocr识别的实现教程
  • 在web-view 加载的本地及远程HTML中调用uniapp的API及网页和vue页面是如何通讯的?
  • 20250606-C#知识:List排序
  • LangChain【6】之输出解析器:结构化LLM响应的关键工具
  • Vue3 卡片绑定滚动条 随着滚动条展开效果 GSAP动画库 ScrollTrigger滚动条插件
  • 【数据结构】B树