怎么才能将文件流或者图片转化为base64,传到前台展示

图片转化为base64,传到前台展示

public String getBase64(){
String imgStr = "";
try { File file = new File("C:\\EThinkTankFile\\20180402160120431.jpg");
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
int offset = 0;
int numRead = 0;
while (offset < buffer.length && (numRead = fis.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
} if (offset != buffer.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
fis.close();
BASE64Encoder encoder = new BASE64Encoder();
imgStr = encoder.encode(buffer);
} catch (Exception e) {
e.printStackTrace();
}
     return "data:image/jpeg;base64,"+imgStr;
}前台代码:<img id="picture" width="690" height="460" src="">通过ajax 请求将后台返回的字符串 添加到src属性中去 $("#picture").attr("src","后台返回的base64字符串");

文件流转化为base64,传到前台展示

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) {
LOGGER.error("InputStream转换成base64失败:{}", e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
LOGGER.error("InputStream转换成base64失败:{}", e);
}
}
}
//返回的字符串传到前台,添加到src属性中去,即可显示图片
return "data:image/jpeg;base64,"+ new String(Base64.encodeBase64(data));
}
上一篇:(转)基于CAS实现单点登录(SSO):cas client端的退出问题


下一篇:Why And When To Use Pre-Update and Pre-Insert Triggers In Oracle Forms