工作中有这样一个需求,在推送给用户的信息中,图片要以base64方式推送,已知图片已上传到minio服务器,图片可根据http地址进行访问…
直接上代码,开干
byte[] buffer = null;
InputStream inputStream = null;
String picurl = "http://xxxxxxxx";
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();){
// 创建URL
URL picurl = new URL(picurl );
// 创建链接
HttpURLConnection conn = (HttpURLConnection) picurl.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
inputStream = conn.getInputStream();
// 将内容读取内存中
buffer = new byte[1024];
int len = -1;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
buffer = outputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
// 关闭inputStream流
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 对字节数组进行Base64编码
Base64.Encoder encode = Base64.getEncoder();
String code = encode.encodeToString(buffer);
通过上诉代码即可完成http地址转base64 的操作,亲测有用.
读者需要注意,图片转base64时,文件太大,转成的base64后长度非常大,应尽量避免转base64操作.