java如何通过流读取图片做base64编码
通过流读取图片做base64编码
在web页面上,显示图片,一般是给出图片地址,然后以url的方式显示,但是有一些特殊情况,如果我们的图片保存在ftp服务器上,不能外部轻易访问,但是可以通过用户名密码的方式登录ftp服务器,然后下载图片,但是这种方式需要将图片另存一份,然后以路径或者url的方式返回给前端页面展示,有一种方式,读取图片流数据,然后将二进制数据做base64编码,最后交给页面显示。
<img src="data:image/png;base64,xxxxxxxxxxxxxxxxxxxxxxx"/>
就可以显示图片了,目前很多地方都使用这种方式展示图片。
案例
下面是一个java读取图片流数据,并通过base64编码工具编码的代码:
package com.xxx.test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import sun.misc.BASE64Encoder;
public class ReadImageInputStreamDemo {
public static void main(String[] args) {
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
try {
String fileName = "/Users/buejee/Downloads/电路.jpeg";
String mediaType = fileName.substring(fileName.lastIndexOf(".")+1);
File imageFile= new File(fileName);
boolean exists = imageFile.exists();
if(exists) {
inputStream = new FileInputStream(fileName);
outputStream = new ByteArrayOutputStream();
int len;
byte[] buf = new byte[1024];
while((len = inputStream.read(buf))!=-1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
byte[] data = outputStream.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
String encodeStr = encoder.encode(data);
encodeStr = "data:image/"+mediaType+";base64,"+encodeStr;
System.out.println(encodeStr);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(inputStream!=null) {
inputStream.close();
}
if(outputStream!=null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}运行代码,可以看到打印信息:

这个图片原图是这样的:

生成的base64编码经过加工,添加data:image/jpeg;base64,然后就可以放到img标签上作为图片显示了。
做一个简单的html页面,内容如下:

最后,通过浏览器打开这个网页:

这样生成的图片base64字符串会很长,在拷贝的时候可能会因为空格问题导致最终显示失败。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
MyBatis-Plus如何通过注解使用TypeHandler
这篇文章主要介绍了MyBatis-Plus如何通过注解使用TypeHandler,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-01-01
springboot结合ehcache防止恶意刷新请求的实现
这篇文章主要介绍了springboot结合ehcache防止恶意刷新请求的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-12-12
Springboot之@ConfigurationProperties注解解读
在Spring Boot中,@EnableConfigurationProperties注解的主要作用是激活@ConfigurationProperties注解的配置属性类,从而让配置属性类能被Spring容器管理,这样的话,我们就可以在属性类中轻松地使用@ConfigurationProperties来绑定配置文件中的属性2024-10-10


最新评论