这篇文章主要介绍“怎么将InputStream转化为base64”,在日常操作中,相信很多人在怎么将InputStream转化为base64问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么将InputStream转化为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));
}
}
项目是基于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";
}
用的是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>
到此,关于“怎么将InputStream转化为base64”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。