In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
这篇文章主要介绍"怎么将InputStream转化为base64",在日常操作中,相信很多人在怎么将InputStream转化为base64问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"怎么将InputStream转化为base64"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
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 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编码的图片。
登录
see the effect
At this point, the study of "how to convert InputStream to base64" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.