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

《博客目录》

[1. 博客前言](#1. 博客前言)

[2. 参考链接](#2. 参考链接)

[3. 核心代码](#3. 核心代码)

[4. 运行效果](#4. 运行效果)

[5. 完整代码](#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() {
  // 获取 resourceManager
  let resManager = this.getUIContext().getHostContext()?.resourceManager;
  // 通过资源ID获取 DrawableDescriptor
  let drawableDesc: DrawableDescriptor =
    resManager?.getDrawableDescriptor($r('app.media.huawei').id) as DrawableDescriptor;
  // 获取 PixelMap
  this.pixelMap = drawableDesc?.getPixelMap();
}

async getPixelMapFromResource(context: Context) {
  // 1. 获取 resourceManager
  const resourceMgr = context.resourceManager;
  // 2. 获取媒体内容的 ArrayBuffer
  const fileData = await resourceMgr.getMediaContent($r('app.media.pingguo').id);
  const buffer = fileData.buffer;
  // 3. 创建 ImageSource 并解码为 PixelMap
  const 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 queried
      predicates.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 Thumbnail
            photoAsset.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() {
    // 获取 resourceManager
    let resManager = this.getUIContext().getHostContext()?.resourceManager;
    // 通过资源ID获取 DrawableDescriptor
    let drawableDesc: DrawableDescriptor =
      resManager?.getDrawableDescriptor($r('app.media.huawei').id) as DrawableDescriptor;
    // 获取 PixelMap
    this.pixelMap = drawableDesc?.getPixelMap();
  }

  async getPixelMapFromResource(context: Context) {
    // 1. 获取 resourceManager
    const resourceMgr = context.resourceManager;
    // 2. 获取媒体内容的 ArrayBuffer
    const fileData = await resourceMgr.getMediaContent($r('app.media.pingguo').id);
    const buffer = fileData.buffer;
    // 3. 创建 ImageSource 并解码为 PixelMap
    const 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 queried
        predicates.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 Thumbnail
              photoAsset.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)
  }
}

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

相关推荐
程序猿追17 分钟前
【鸿蒙PC桌面端实战】从零构建 ArkTS 高性能图像展示器:DevEco Studio 调试与 HDC 命令行验证全流程
华为·harmonyos
前端世界1 小时前
设备找不到、Ability 启不动?一次讲清 DevEco Studio 调试鸿蒙分布式应用
华为·harmonyos
行者962 小时前
OpenHarmony上Flutter粒子效果组件的深度适配与实践
flutter·交互·harmonyos·鸿蒙
小溪彼岸2 小时前
uni-app小白从0开发一款鸿蒙Next应用到上线
uni-app·harmonyos
高心星3 小时前
鸿蒙6.0应用开发——仿微博文本折叠
鸿蒙·折叠·鸿蒙6.0·harmonyos6.0·文本折叠
asing3 小时前
🤯 为什么我的收银台在鸿蒙系统“第一次返回”死活拦不住?一次差点背锅的排查实录
前端·harmonyos
Van_captain4 小时前
rn_for_openharmony常用组件_Breadcrumb面包屑
javascript·开源·harmonyos
御承扬4 小时前
鸿蒙原生系列之动画效果(帧动画)
c++·harmonyos·动画效果·ndk ui·鸿蒙原生
行者965 小时前
Flutter与OpenHarmony深度集成:数据导出组件的实战优化与性能提升
flutter·harmonyos·鸿蒙
小雨下雨的雨5 小时前
Flutter 框架跨平台鸿蒙开发 —— Row & Column 布局之轴线控制艺术
flutter·华为·交互·harmonyos·鸿蒙系统