• 【ARK UI】HarmonyOS ETS如何创建PixeMap并显示Image组件上


    ​参考资料

    图片处理

    Context模块

    api讲解

    image.createPixelMap

    createPixelMap(number: fd, options: InitializationOptions): Promise

    通过属性创建PixelMap,通过Promise返回结果。

    系统能力: SystemCapability.Multimedia.Image

    参数:

    cke_658.png

    返回值:

    cke_1421.png

    示例:

      image.createPixelMap(fd, opts).then((pixelMap) => {
         this. mypixemap=pixelMap
       }).catch((err) => {
         console.log("create pixelMap with data fail: " + err.data)
       })

     

    代码实现

    • 准备工作

      1.准备一张图片放在rawfile文件目录,如下图所示

       

      cke_4137.png

      cke_5027.png

       

    • 申请权限

      在config.json注册如下权限代码如下

      "reqPermissions": [
        {
          "name": "ohos.permission.READ_USER_STORAGE"
        },
        {
          "name": "ohos.permission.WRITE_USER_STORAGE"
        },
        {
          "name": "ohos.permission.SET_WALLPAPER"
        }
      ],

      在mainAbility注册申请权限,并把图片写入指定文件夹目录下,代码如下

      package com.newdemo.myapplication;
      
      import ohos.ace.ability.AceAbility;
      import ohos.aafwk.content.Intent;
      import ohos.global.resource.RawFileEntry;
      import ohos.global.resource.Resource;
      
      import java.io.File;
      import java.io.FileOutputStream;
      import java.io.IOException;
      
      public class MainAbility extends AceAbility {
          @Override
          public void onStart(Intent intent) {
              String[] permissions = {
                      "ohos.permission.WRITE_USER_STORAGE",
                      "ohos.permission.READ_USER_STORAGE"
              };
              requestPermissionsFromUser(permissions, 0);
              super.onStart(intent);
              writeToDisk( "entry/resources/rawfile/result.png","/result.png");
          }
      
          private void writeToDisk(String rawFilePath, String resultpath) {
              String externalFilePath = getFilesDir() +resultpath ;
              File file = new File(externalFilePath);
              if (file.exists()) {
                  return;
              }
              RawFileEntry rawFileEntry = getResourceManager().getRawFileEntry(rawFilePath);
              try (FileOutputStream outputStream = new FileOutputStream(new File(externalFilePath))) {
                  Resource resource = rawFileEntry.openRawFile();
                  // cache length
                  byte[] cache = new byte[1024];
                  int len = resource.read(cache);
                  while (len != -1) {
                      outputStream.write(cache, 0, len);
                      len = resource.read(cache);
                  }
              } catch (IOException exception) {
              }
          }
      }
    • Ets语言实现

      在组件加载完成之前(aboutToAppear函数)把图片路径转场pixeMap并显示Image组件上,代码如下

      import image from '@ohos.multimedia.image';
      import fileio from '@ohos.fileio';
      import featureAbility from '@ohos.ability.featureAbility'
      
      @Entry
      @Component
      struct ImagePages {
        //todo 自定义PixelMap 对象
        @State mypixemap: PixelMap= undefined;
        //todo 在组件加载前aboutToAppear的吧路径转化为pixemap
        public aboutToAppear() {
          //todo 获取context环境
          let context = featureAbility.getContext();
          //todo 获取当前files路基
          context.getFilesDir((err, data) => {
            if (err) {
              console.error('Operation failed. Cause: ' + JSON.stringify(err));
              return;
            }
            console.info('Operation successful. Data:' + JSON.stringify(data));
            //todo 得到fd
            let fd = fileio.openSync(data + "/result.png")
            console.log('fd: ' + fd)
            //todo 自定义opts参数
            let defaultSize = {
              "height": 226,
              "width": 405
            }
            let opts = {
              "sampleSize": 1,
              "rotate": 0,
              "editable": true,
              "desiredSize": defaultSize,
              "desiredRegion": {
                "size": defaultSize,
                "x": 0,
                "y": 0
              },
              "desiredPixelFormat": 3,
            };
            //todo 创建pixeMap对象
            image.createPixelMap(fd, opts).then((pixelMap) => {
              //todo 创建成果
              this.mypixemap = pixelMap
            }).catch((err) => {
              //todo 创建失败
              console.log("create pixelMap with data fail: " + err.data)
            })
          });
        }
      
        build() {
          Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
           //todo  把pixeMap 显示在Image组件上
            Image(this.mypixemap).width(405).height(226)
          }
          .width('100%')
          .height('100%')
        }
      }

       

      运行效果

      cke_15929.png

    欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

  • 相关阅读:
    WebGL层次模型——单节点模型
    Unity开发3
    js深浅拷贝:保证赋值后改变第二个变量的值,不影响第一个变量的值
    运放注意事项
    Vant的List组件列表 滑动后不触底也发送请求的Bug
    Leetcode---368周赛
    VBA学习(17):使用条件格式制作Excel聚光灯
    几个适合Java开发者的免费IDEA插件
    Stream 流式编程 ( Java 8新特性 )
    新手指南|如何快速参与Moonbeam Ignite
  • 原文地址:https://www.cnblogs.com/developer-huawei/p/16593770.html