【HarmonyOS】【JAVA UI】鸿蒙怎么对图片编码为 base64 和 base64 解码为 PixelMap,并显示在控件上
2023-09-11 14:17:17 时间
在 HarmonyOS 中对图片的解码和编码是常见的操作,在 HarmonyOS 怎么进行编码和解码呢?今天写一个 demo 进行实现该功能实现,我们从以下几个步骤进行讲解该功能
1. 准备环节
2. 图片编码为 Base64 字符串
3. Base64 解码为 PixelMap,并显示在 Image 控件上
第一步准备环节
1.1 准备一张图片放在 resources/rawfile 文件夹下,图片如下
1.2 新建 ImageAbilitySlice java 类和 xml 布局, xml 布局如下
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:orientation="vertical">
<Text
ohos:height="100vp"
ohos:width="match_parent"
ohos:background_element="#ffffff"
ohos:text="图片编码"
ohos:text_size="20vp"
ohos:text_alignment="center"
ohos:id="$+id:textRead"/>
<Text
ohos:id="$+id:getmPixelMapAndShowImage"
ohos:height="100vp"
ohos:width="match_parent"
ohos:text="图片解码并显示"
ohos:background_element="#ed6262"
ohos:text_size="20vp"
ohos:text_alignment="center"/>
<Image
ohos:height="match_parent"
ohos:width="match_parent"
ohos:id="$+id:ShowImage"/>
</DirectionalLayout>
XML 效果图如下
第二步图片编码为 Base64 字符串
2.1 这边我们参考资料是 Base64 的基本用法,来写一个工具类,代码如下
package com.harmony.alliance.mydemo.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
public class ImageUtils {
/**
* 将图片转换成Base64编码的字符串
*/
public static String imageToBase64(String path) {
if(path==null||path.equals("")) {
return null;
}
InputStream is = null;
byte[] data = null;
String result = null;
try {
is = new FileInputStream(path);
//创建一个字符流大小的数组。
data = new byte[is.available()];
//写入数组
is.read(data);
//用默认的编码格式进行编码
result = Base64.getEncoder().encodeToString(data);
}catch (Exception e) {
e.printStackTrace();
}finally {
if(null !=is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* 将图片转换成Base64编码的字符串
*/
public static String imageInputStreamToBase64( InputStream is) {
if(is==null) {
return null;
}
byte[] data = null;
String result = null;
try {
//创建一个字符流大小的数组。
data = new byte[is.available()];
//写入数组
is.read(data);
//用默认的编码格式进行编码
result = Base64.getEncoder().encodeToString(data);
}catch (Exception e) {
e.printStackTrace();
}finally {
if(null !=is){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}
2.2 实现图片编码的代码如下
textRead.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
try {
String filePath = String.format(Locale.ROOT, "assets/entry/resources/rawfile/%s", "icon.png");
InputStream is = this.getClass().getClassLoader().getResourceAsStream(filePath);
//Todo 得到base64字符串
ImageData="data:image/png;base64,"+ ImageUtils.imageInputStreamToBase64(is);
HiLogUtils.PrintLog(ImageData);
}catch (Exception e) {
e.printStackTrace();
}
}
});
效果图如下
第三步将 Base64 解码为 mPixelMap 并显示在 Image 控件上
3.1 我们这里使用如下 Base64.getDecoder().decode 和 ImageSource、SourceOptions 的相关技术,代码如下
findComponentById(ResourceTable.Id_getmPixelMapAndShowImage).setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
String Base64Data= ImageData.replace("data:image/png;base64,","");
//todo base64字符串得到字节
byte[] base64byte= java.util.Base64.getDecoder().decode(Base64Data);
ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
srcOpts.formatHint = "image/png";
ImageSource imageSource = ImageSource.create(base64byte, srcOpts);
// 设置图片参数
ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
PixelMap mPixelMap = imageSource.createPixelmap(decodingOptions);
ShowImage.setPixelMap(mPixelMap);
}
});
效果图如下
整体代码如下
package com.harmony.alliance.mydemo.slice;
import com.harmony.alliance.mydemo.ResourceTable;
import com.harmony.alliance.mydemo.utils.ImageUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.Locale;
public class ImageAbilitySlice extends AbilitySlice {
Image ShowImage;
private String ImageData;
@Override
protected void onStart(Intent intent) {
super.onStart(intent);
setUIContent(ResourceTable.Layout_iamge_ability_slice);
Text textRead= (Text) findComponentById(ResourceTable.Id_textRead);
ShowImage= (Image) findComponentById(ResourceTable.Id_ShowImage);
textRead.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
try {
String filePath = String.format(Locale.ROOT, "assets/entry/resources/rawfile/%s", "icon.png");
InputStream is = this.getClass().getClassLoader().getResourceAsStream(filePath);
//Todo 得到base64字符串
ImageData="data:image/png;base64,"+ ImageUtils.imageInputStreamToBase64(is);
HiLogUtils.PrintLog(ImageData);
}catch (Exception e){
e.printStackTrace();
}
}
});
findComponentById(ResourceTable.Id_getmPixelMapAndShowImage).setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
String Base64Data= ImageData.replace("data:image/png;base64,","");
//todo base64字符串得到字节
byte[] base64byte= java.util.Base64.getDecoder().decode(Base64Data);
ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
srcOpts.formatHint = "image/png";
ImageSource imageSource = ImageSource.create(base64byte, srcOpts);
// 设置图片参数
ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
PixelMap mPixelMap = imageSource.createPixelmap(decodingOptions);
ShowImage.setPixelMap(mPixelMap);
}
});
}
}
效果如下
相关文章
- java安全编码指南之:拒绝Denial of Service
- Java核心技术卷I基础知识3.8.6 中断控制流程语句
- Java 7中的TransferQueue
- [转]Java中导入、导出Excel
- Java项目(前端vue后台java微服务)在线考试系统(java+vue+springboot+mysql+maven)
- Some Java exceptions, messages and errors.
- java 8 处理字符拼接有null问题
- 报错:java.lang.ArithmeticException:divide by zero
- maven项目的java和resources等文件夹不在Java Resources的文件夹里,并且缺少Deployment...
- 《Java编码指南:编写安全可靠程序的75条建议》—— 指南19:对细粒度的安全定义自定义安全权限
- Java List/Set/Map
- Java bit、byte、位、字节、汉字、字符
- 小编辑 Java 中十进制和十六进制的相互转换
- java中文乱码解决之道(二)—–字符编码详解:基础知识 + ASCII + GB**
- Java 设计模式之桥接模式,Java 桥接模式 ,java Bridge Pattern
- java安全编码指南之:声明和初始化
- java如何判断编码是否是utf8编码
- java使用序列化实现深克隆
- 无人机航拍照片定位技术实现--含Java与Cesium实现
- java学习-http中get请求的非ascii参数如何编码解码探讨
- 浅析Java中可变长参数的优势及其使用注意事项
- java学习路线-Java技术人员之路从0基础到高级
- java编码问题总结
- 孙悟空的七十二变是那般?--java类型的七十二变揭秘
- 深入分析 Java 中的中文编码问题--转
- Java IDEA 项目运行着 突然整个项目文件就没了 网站都还在运行着哦
- Java Annotation —— 注解实战