目录
- inputstream转化为base64
- 项目经常会用到将文件转化为base64进行传输
- 把文件流转base64,然后前端展示base64图片
- java端
- html端
- 看效果
inputstream转化为base64
项目经常会用到将文件转化为base64进行传输
怎么才能将文件流转化为base64呢,代码如下
/**
* @author 李光光(编码小王子)
* @date 2018年6月28日 下午2:09:26
* @version 1.0
*/
public class filetobase64 {
public static string getbase64frominputstream(inputstream in) {
// 将图片文件转化为字节数组字符串,并对其进行base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
bytearrayoutputstream swapstream = new bytearrayoutputstream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
swapstream.write(buff, 0, rc);
}
data = swapstream.tobytearray();
} catch (ioexception e) {
e.printstacktrace();
} finally {
if (in != null) {
try {
in.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
}
return new string(base64.encodebase64(data));
}
}
把文件流转base64,然后前端展示base64图片
java端
项目是基于springboot的。读取本地图片,转成base64编码字节数组字符串,传到前端。
这种传输图片的方式可以用于java后台代码生成条形码二维码,直接转成base64传给前台展示。ps:(在传给前台的字符串前要加上data:image/png;base64,,这样html的img标签的src才能以图片的格式去解析字符串)
@requestmapping("/login")
public string login(map<string ,object> map){
byte[] data = null;
// 读取图片字节数组
try {
inputstream in = new fileinputstream("e://aa.jpg");
data = new byte[in.available()];
in.read(data);
in.close();
} catch (ioexception e) {
e.printstacktrace();
}
// 对字节数组base64编码
base64encoder encoder = new base64encoder();
// 返回base64编码过的字节数组字符串
map.put("image","data:image/png;base64,"+ encoder.encode(objects.requirenonnull(data)));
return "login";
}
html端
用的是thymeleaf模板引擎,只是单纯地展示base64编码的图片。
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>登录</title>
</head>
<body>
<img th:src="${image}">
</body>
</html>
看效果
以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。