实例:
1.后台代码:base64加密与解密
imgUrl为可以访问的图片网络地址
package com.bootdo.seal.utils;
import io.netty.util.internal.StringUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by jq on 2019/2/20.
*/
public class Base64 {
/**
* 远程读取image转换为Base64字符串
*
* @param imgUrl
* @return
*/
public static String image2Base64(String imgUrl) {
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
// 创建URL
URL url = new URL(imgUrl);
byte[] by = new byte[1024];
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
InputStream is = conn.getInputStream();
// 将内容读取内存中
int len = -1;
while ((len = is.read(by)) != -1) {
data.write(by, 0, len);
}
// 关闭流
is.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data.toByteArray()).replaceAll("[\\s*\t\n\r]", "");
}
// 将base64编码字符串转换为图片(不含有data:image/jpeg;base64,这样的前缀,如果有用逗号做分割,取逗号后面的数据)
// imgStr base64编码字符串 path 图片路径-具体到文件
public static boolean base64ToImage(String imgStr, String path) {
if (imgStr == null){
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(imgStr);// 解密
for (int i = 0; i < b.length; ++i) {
if (b < 0){
b += 256;//调整异常数据
}
}
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static void main(String[] args) {
//加密后字符串
String imgStr = "";
String imgFilePath = "F:\\doc\\new.png";
base64ToImage(imgStr, imgFilePath);
}
}
2.前台代码:在前台页面上使用:
<img id="img2" th:src="@{'data:image/jpg;base64,'+${base64Str}}">
base64的字符串前一定要加《 data:image/jpg;base64, 》注意:有逗号
才能被浏览器正确解析识别
---------------------
【转载,仅作分享,侵删】
作者:xinyuebaihe
原文:https://blog.csdn.net/xinyuebaihe/article/details/88189827
版权声明:本文为博主原创文章,转载请附上博文链接!
|
|