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

鸿蒙:将Resource类型的image转成 image.PixelMap 类型

《博客目录》

1. 博客前言

2. 参考链接

3. 核心代码

4. 运行效果

5. 完整代码


1. 前言

有些时候,我们使用某些显示图片的组件时,发现只能填入image.PixelMap格式的图片,此时,我们需要转换类型。本篇博客,分享Resource 类型如何转换成image.PixelMap 类型(或获取Resource图片的PixelMap)。

2. 参考链接

https://developer.huawei.com/consumer/cn/forum/topic/0203192799649268451?fid=0109140870620153026https://developer.huawei.com/consumer/cn/forum/topic/0203192799649268451?fid=0109140870620153026

https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-image-6https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-image-6

3. 核心代码

getImagePixelMap1() {// 获取 resourceManagerlet resManager = this.getUIContext().getHostContext()?.resourceManager;// 通过资源ID获取 DrawableDescriptorlet drawableDesc: DrawableDescriptor =resManager?.getDrawableDescriptor($r('app.media.huawei').id) as DrawableDescriptor;// 获取 PixelMapthis.pixelMap = drawableDesc?.getPixelMap();
}
async getPixelMapFromResource(context: Context) {// 1. 获取 resourceManagerconst resourceMgr = context.resourceManager;// 2. 获取媒体内容的 ArrayBufferconst fileData = await resourceMgr.getMediaContent($r('app.media.pingguo').id);const buffer = fileData.buffer;// 3. 创建 ImageSource 并解码为 PixelMapconst imageSource = image.createImageSource(buffer);this.pixelMap2 = await imageSource.createPixelMap();}
getPixelMap3() {try {let uris: Array<string> = [];let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;PhotoSelectOptions.maxSelectNumber = 1;let photoPicker = new photoAccessHelper.PhotoViewPicker();photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {console.info('photoPicker.select successfully, PhotoSelectResult uri: ' +JSON.stringify(PhotoSelectResult));uris = PhotoSelectResult.photoUris;let phAccessHelper =photoAccessHelper.getPhotoAccessHelper(this.getUIContext().getHostContext() as Context);let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();// Configure query conditions, use PhotoViewPicker to select the URI of the image to be queriedpredicates.equalTo('uri', uris[0]);let fetchOptions: photoAccessHelper.FetchOptions = {fetchColumns: [],predicates: predicates};phAccessHelper.getAssets(fetchOptions, async (err, fetchResult) => {if (fetchResult !== undefined) {console.info('fetchResult success');let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();if (photoAsset !== undefined) {// Get ThumbnailphotoAsset.getThumbnail((err, pixelMap) => {if (err == undefined) {this.pixelMap3 = pixelMap;console.info('getThumbnail successful ' + JSON.stringify(pixelMap));} else {console.error('getThumbnail fail', err);}});console.info('photoAsset.displayName : ' + photoAsset.displayName);}} else {console.error(`fetchResult fail with error: ${err.code}, ${err.message}`);}});}).catch((err: BusinessError) => {console.error('photoPicker.select failed with err: ' + JSON.stringify(err));});} catch (error) {let err: BusinessError = error as BusinessError;console.error('photoPicker failed with err: ' + JSON.stringify(err));}
}

4. 运行效果

5. 完整代码

Index.ets

import { image } from '@kit.ImageKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { dataSharePredicates } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';@Entry
@ComponentV2
struct Index {@Local pixelMap: image.PixelMap | undefined = undefined;@Local pixelMap2: image.PixelMap | undefined = undefined;@Local pixelMap3: image.PixelMap | undefined = undefined;getImagePixelMap1() {// 获取 resourceManagerlet resManager = this.getUIContext().getHostContext()?.resourceManager;// 通过资源ID获取 DrawableDescriptorlet drawableDesc: DrawableDescriptor =resManager?.getDrawableDescriptor($r('app.media.huawei').id) as DrawableDescriptor;// 获取 PixelMapthis.pixelMap = drawableDesc?.getPixelMap();}async getPixelMapFromResource(context: Context) {// 1. 获取 resourceManagerconst resourceMgr = context.resourceManager;// 2. 获取媒体内容的 ArrayBufferconst fileData = await resourceMgr.getMediaContent($r('app.media.pingguo').id);const buffer = fileData.buffer;// 3. 创建 ImageSource 并解码为 PixelMapconst imageSource = image.createImageSource(buffer);this.pixelMap2 = await imageSource.createPixelMap();}getPixelMap3() {try {let uris: Array<string> = [];let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;PhotoSelectOptions.maxSelectNumber = 1;let photoPicker = new photoAccessHelper.PhotoViewPicker();photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {console.info('photoPicker.select successfully, PhotoSelectResult uri: ' +JSON.stringify(PhotoSelectResult));uris = PhotoSelectResult.photoUris;let phAccessHelper =photoAccessHelper.getPhotoAccessHelper(this.getUIContext().getHostContext() as Context);let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();// Configure query conditions, use PhotoViewPicker to select the URI of the image to be queriedpredicates.equalTo('uri', uris[0]);let fetchOptions: photoAccessHelper.FetchOptions = {fetchColumns: [],predicates: predicates};phAccessHelper.getAssets(fetchOptions, async (err, fetchResult) => {if (fetchResult !== undefined) {console.info('fetchResult success');let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();if (photoAsset !== undefined) {// Get ThumbnailphotoAsset.getThumbnail((err, pixelMap) => {if (err == undefined) {this.pixelMap3 = pixelMap;console.info('getThumbnail successful ' + JSON.stringify(pixelMap));} else {console.error('getThumbnail fail', err);}});console.info('photoAsset.displayName : ' + photoAsset.displayName);}} else {console.error(`fetchResult fail with error: ${err.code}, ${err.message}`);}});}).catch((err: BusinessError) => {console.error('photoPicker.select failed with err: ' + JSON.stringify(err));});} catch (error) {let err: BusinessError = error as BusinessError;console.error('photoPicker failed with err: ' + JSON.stringify(err));}}aboutToAppear(): void {this.getImagePixelMap1();this.getPixelMapFromResource(this.getUIContext().getHostContext() as Context);}build() {Column({ space: 80 }) {Column({ space: 20 }) {Text("方式一: DrawableDescriptor ").fontWeight(FontWeight.Medium).fontSize(20)Image(this.pixelMap).width(350)}Column({ space: 20 }) {Text("方式二: resourceManager.getMediaContent ").fontWeight(FontWeight.Medium).fontSize(20)Image(this.pixelMap2).width(100)}Column({ space: 20 }) {Text("方式三: getThumbnail ").fontWeight(FontWeight.Medium).fontSize(20)Button("获取位图").onClick(() => {this.getPixelMap3()})Image(this.pixelMap3).width(100)}}.width("100%").height("100%").justifyContent(FlexAlign.Center)}
}

觉得有帮助,可以点赞或收藏

http://www.dtcms.com/a/520183.html

相关文章:

  • 如何创建自己的网站平台网站项目建设措施
  • 网站论坛制作滕州手机网站建设案例
  • CANoe学习(一)软件安装和基本使用
  • transform和LLM回顾一下知识点(复习笔记(专业:AI))
  • 怎样创建网站或网页ui设计师怎么做自己的网站
  • Java的抽象类实践-模板设计模式
  • 手记鲁班猫树莓派部署python服务
  • 国企员工学PMP完全是多此一举,听劝好吧
  • 【数论】欧拉函数
  • 【工具】Docker 的基础使用
  • 网站流量与广告费编辑wordpress文章页
  • java基础:String字符串的用法详解
  • 唐河网站制作品牌推广文案
  • VSCode/PyCharm解决“无法加载文件 ***\WindowsPowerShell\profile.ps1,因为在此系统上禁止运行脚本”
  • 做设计的需要网站下载素材吗wordpress菜单添加图标
  • HTML游戏开发:使用视频作为特效自动播放的方法
  • 单芯片USB拓展坞+百兆网卡+读卡器+100W快充芯片CH336F
  • 考研数学——一元函数微分学篇
  • MATLAB基于改进灰色聚类的装备技术风险评估方法
  • 最佳经验网站wordpress大学百度云
  • AI服务器工作之显卡测试
  • C++仿mudo库高并发服务器项目:Socket模块
  • 找人帮忙做网站吉林市百姓网免费发布信息网
  • HTTP与HTTPS协议区别及应用场景
  • HTTP 206状态码:部分内容传输核心技术
  • Vue3 -- 第一个vue项目
  • 收钱码合并的网站怎么做电商网站产品模块
  • Vitis HLS 学习指南与实践教程
  • FBH公司开发了200 MHz GaN降压变换器模块
  • SpiderDemo题解系列——第3篇:调试拦截与非对称加密挑战 — JS逆向调试实战(第23题)