解决微信头像跨域问题

本文介绍了在项目中遇到微信头像跨域问题的背景,提出了解决方案,即通过将微信头像转换为BASE64编码来规避跨域限制。文章详细讲述了使用JAVA实现图片URL转成BASE64的过程,并提供了在HTML页面中应用的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景介绍
解决方案

将微信头像转成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的内容);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑾析编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值