背景介绍
- 微信头像链接:http://thirdwx.qlogo.cn/mmopen/vi_32/xxxxxx
- 项目域名:http://xxx.xxx.com
- 现在要将页面生成图片,会报跨域问题
解决方案
将微信头像转成BASE64的文件
具体实现
- JAVA 将图片URL转成BASE64
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.List;
// 其它代码
private String getImage(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编码
return Base64.getEncoder().encodeToString(data.toByteArray());
}
- HTML页面使用方式
$('#myHeadImageUrl').attr('src', 'data:image/png;base64,' + BASE64的内容);