使用原因
图片存储于内部服务器,但是其中某些特殊图片需要允许外网访问。
采取以下方式:
从内部服务器获取到图片—>图片转base64—>给前端
实际操作
/**
* 将url上图片转Base64
* @param fileUrl 图片地址
* @param ss 图片后缀,如png,jpg等
* @throws Exception 异常
*/
public static String imageToBase64(String fileUrl,String ss) throws Exception {
//打开链接
URL url = new URL(fileUrl);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(3000);
InputStream inStream = connection.getInputStream();
//得到图片的二进制数据
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
//关闭输入流
inStream.close();
byte[] picData = new byte[0];
picData = outStream.toByteArray();
if(picData.length == 0){
log.error("图片数据大小为0,url地址为{}",fileUrl);
}
return "data:image/"+ss+";base64,"+Base64.getEncoder().encodeToString(picData);
}