• 【HarmonyOS】【JAVA UI】鸿蒙怎么对图片编码为base64和base64解码为PixelMap,并显示在控件上


     在HarmonyOS中对图片的解码和编码是常见的操作,在HarmonyOS怎么进行编码和解码呢?今天写一个demo进行实现该功能实现,我们从以下几个步骤进行讲解该功能

    1.       准备环节

    2.       图片编码为Base64字符串

    3.       Base64解码为PixelMap,并显示在Image控件上

    第一步准备环节

    1.1    准备一张图片放在resources/rawfile文件夹下,图片如下

    image.png

    1.2 新建ImageAbilitySlice java类和xml布局, xml布局如下

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <DirectionalLayout
    3. xmlns:ohos="http://schemas.huawei.com/res/ohos"
    4. ohos:height="match_parent"
    5. ohos:width="match_parent"
    6. ohos:orientation="vertical">
    7. <Text
    8. ohos:height="100vp"
    9. ohos:width="match_parent"
    10. ohos:background_element="#ffffff"
    11. ohos:text="图片编码"
    12. ohos:text_size="20vp"
    13. ohos:text_alignment="center"
    14. ohos:id="$+id:textRead"/>
    15. <Text
    16. ohos:id="$+id:getmPixelMapAndShowImage"
    17. ohos:height="100vp"
    18. ohos:width="match_parent"
    19. ohos:text="图片解码并显示"
    20. ohos:background_element="#ed6262"
    21. ohos:text_size="20vp"
    22. ohos:text_alignment="center"/>
    23. <Image
    24. ohos:height="match_parent"
    25. ohos:width="match_parent"
    26. ohos:id="$+id:ShowImage"/>
    27. </DirectionalLayout>

    XML效果图如下

    image.png

    第二步图片编码为Base64字符串

    2.1这边我们参考资料是Base64的基本用法,来写一个工具类,代码如下

    1. package com.harmony.alliance.mydemo.utils;
    2. import java.io.FileInputStream;
    3. import java.io.IOException;
    4. import java.io.InputStream;
    5. import java.util.Base64;
    6. public class ImageUtils {
    7. /**
    8. * 将图片转换成Base64编码的字符串
    9. */
    10. public static String imageToBase64(String path){
    11. if(path==null||path.equals("")){
    12. return null;
    13. }
    14. InputStream is = null;
    15. byte[] data = null;
    16. String result = null;
    17. try{
    18. is = new FileInputStream(path);
    19. //创建一个字符流大小的数组。
    20. data = new byte[is.available()];
    21. //写入数组
    22. is.read(data);
    23. //用默认的编码格式进行编码
    24. result = Base64.getEncoder().encodeToString(data);
    25. }catch (Exception e){
    26. e.printStackTrace();
    27. }finally {
    28. if(null !=is){
    29. try {
    30. is.close();
    31. } catch (IOException e) {
    32. e.printStackTrace();
    33. }
    34. }
    35. }
    36. return result;
    37. }
    38. /**
    39. * 将图片转换成Base64编码的字符串
    40. */
    41. public static String imageInputStreamToBase64( InputStream is){
    42. if(is==null){
    43. return null;
    44. }
    45. byte[] data = null;
    46. String result = null;
    47. try{
    48. //创建一个字符流大小的数组。
    49. data = new byte[is.available()];
    50. //写入数组
    51. is.read(data);
    52. //用默认的编码格式进行编码
    53. result = Base64.getEncoder().encodeToString(data);
    54. }catch (Exception e){
    55. e.printStackTrace();
    56. }finally {
    57. if(null !=is){
    58. try {
    59. is.close();
    60. } catch (IOException e) {
    61. e.printStackTrace();
    62. }
    63. }
    64. }
    65. return result;
    66. }
    67. }

    2.2实现图片编码的代码如下

    1. textRead.setClickedListener(new Component.ClickedListener() {
    2. @Override
    3. public void onClick(Component component) {
    4. try {
    5. String filePath = String.format(Locale.ROOT, "assets/entry/resources/rawfile/%s", "icon.png");
    6. InputStream is = this.getClass().getClassLoader().getResourceAsStream(filePath);
    7. //Todo 得到base64字符串
    8. ImageData="data:image/png;base64,"+ ImageUtils.imageInputStreamToBase64(is);
    9. HiLogUtils.PrintLog(ImageData);
    10. }catch (Exception e){
    11. e.printStackTrace();
    12. }
    13. }
    14. });

    效果图如下

    image.png

    第三步将Base64解码为mPixelMap并显示在Image控件上

    3.1我们这里使用如下Base64.getDecoder().decodeImageSourceSourceOptions的相关技术,代码如下

    1. findComponentById(ResourceTable.Id_getmPixelMapAndShowImage).setClickedListener(new Component.ClickedListener() {
    2. @Override
    3. public void onClick(Component component) {
    4. String Base64Data= ImageData.replace("data:image/png;base64,","");
    5. //todo base64字符串得到字节
    6. byte[] base64byte= java.util.Base64.getDecoder().decode(Base64Data);
    7. ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
    8. srcOpts.formatHint = "image/png";
    9. ImageSource imageSource = ImageSource.create(base64byte, srcOpts);
    10. // 设置图片参数
    11. ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
    12. PixelMap mPixelMap = imageSource.createPixelmap(decodingOptions);
    13. ShowImage.setPixelMap(mPixelMap);
    14. }
    15. });

    效果图如下

    image.png

    整体代码如下

    1. package com.harmony.alliance.mydemo.slice;
    2. import com.harmony.alliance.mydemo.ResourceTable;
    3. import com.harmony.alliance.mydemo.utils.ImageUtils;
    4. import ohos.aafwk.ability.AbilitySlice;
    5. import ohos.aafwk.content.Intent;
    6. import ohos.agp.components.Component;
    7. import ohos.agp.components.Image;
    8. import ohos.agp.components.Text;
    9. import ohos.global.resource.RawFileEntry;
    10. import ohos.global.resource.Resource;
    11. import ohos.media.image.ImageSource;
    12. import ohos.media.image.PixelMap;
    13. import java.io.File;
    14. import java.io.FileOutputStream;
    15. import java.io.IOException;
    16. import java.io.InputStream;
    17. import java.util.Base64;
    18. import java.util.Locale;
    19. public class ImageAbilitySlice extends AbilitySlice {
    20. Image ShowImage;
    21. private String ImageData;
    22. @Override
    23. protected void onStart(Intent intent) {
    24. super.onStart(intent);
    25. setUIContent(ResourceTable.Layout_iamge_ability_slice);
    26. Text textRead= (Text) findComponentById(ResourceTable.Id_textRead);
    27. ShowImage= (Image) findComponentById(ResourceTable.Id_ShowImage);
    28. textRead.setClickedListener(new Component.ClickedListener() {
    29. @Override
    30. public void onClick(Component component) {
    31. try {
    32. String filePath = String.format(Locale.ROOT, "assets/entry/resources/rawfile/%s", "icon.png");
    33. InputStream is = this.getClass().getClassLoader().getResourceAsStream(filePath);
    34. //Todo 得到base64字符串
    35. ImageData="data:image/png;base64,"+ ImageUtils.imageInputStreamToBase64(is);
    36. HiLogUtils.PrintLog(ImageData);
    37. }catch (Exception e){
    38. e.printStackTrace();
    39. }
    40. }
    41. });
    42. findComponentById(ResourceTable.Id_getmPixelMapAndShowImage).setClickedListener(new Component.ClickedListener() {
    43. @Override
    44. public void onClick(Component component) {
    45. String Base64Data= ImageData.replace("data:image/png;base64,","");
    46. //todo base64字符串得到字节
    47. byte[] base64byte= java.util.Base64.getDecoder().decode(Base64Data);
    48. ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
    49. srcOpts.formatHint = "image/png";
    50. ImageSource imageSource = ImageSource.create(base64byte, srcOpts);
    51. // 设置图片参数
    52. ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
    53. PixelMap mPixelMap = imageSource.createPixelmap(decodingOptions);
    54. ShowImage.setPixelMap(mPixelMap);
    55. }
    56. });
    57. }
    58. }

    效果如下

    image.png

    更多相关学习资料:
    https://developer.huawei.com/consumer/cn/forum/topic/0202768644032900242?fid=0102683795438680754?ha_source=zzh

  • 相关阅读:
    外贸业务员如何通过google搜索多个关键词批量提取客户网址?
    第八章 动态规划 3 AcWing 1554. 找更多硬币
    Allergo导出Gerber文件
    如何防止网络安全攻击
    SDRAM控制器——添加读写FIFO
    DGIOT实战教程——虚拟Modbus TCP接入
    高效时代,电商运营如何靠RPA快速提效?
    面向对象编程原则(10)——总结
    Docker---Docker-compose 安装部署 minio 存储服务
    JAVA编程规范之应用分层
  • 原文地址:https://blog.csdn.net/weixin_44708240/article/details/125621506