前言

项目使用了MINIO对象存储,但是导出的外链,前端无法直接显示,所以需要后端处理下载,然后转成base64格式

代码

  1. /**
  2. * 将网络图片编码为base64
  3. *
  4. * @param url
  5. * @return
  6. * @throws BusinessException
  7. */
  8. public static String encodeImageToBase64(String tempUrl) throws Exception {
  9. URL url = new URL(tempUrl);
  10. //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
  11. //打开链接
  12. HttpURLConnection conn = null;
  13. try {
  14. conn = (HttpURLConnection) url.openConnection();
  15. //设置请求方式为"GET"
  16. conn.setRequestMethod("GET");
  17. //超时响应时间为5秒
  18. conn.setConnectTimeout(5 * 1000);
  19. //通过输入流获取图片数据
  20. InputStream inStream = conn.getInputStream();
  21. //得到图片的二进制数据,以二进制封装得到数据,具有通用性
  22. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  23. //创建一个Buffer字符串
  24. byte[] buffer = new byte[1024];
  25. //每次读取的字符串长度,如果为-1,代表全部读取完毕
  26. int len = 0;
  27. //使用一个输入流从buffer里把数据读取出来
  28. while ((len = inStream.read(buffer)) != -1) {
  29. //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
  30. outStream.write(buffer, 0, len);
  31. }
  32. //关闭输入流
  33. inStream.close();
  34. byte[] data = outStream.toByteArray();
  35. //对字节数组Base64编码
  36. BASE64Encoder encoder = new BASE64Encoder();
  37. String base64 = encoder.encode(data);
  38. //注意清洗\n等格式信息,不然不能直接转bae64
  39. base64 = base64.replace("\t", "").replace("\r", "");
  40. base64 = base64.replace("\n", "");
  41. //记得加上前缀
  42. if("jpeg".compareToIgnoreCase(prefix)==0)
  43. {
  44. return "data:image/jpeg;"+"base64,"+base64;
  45. }
  46. else
  47. {
  48. return "data:image/png;"+"base64,"+base64;
  49. }
  50. System.out.println("网络文件[{}]编码成base64字符串:[{}]"+url.toString()+base64);
  51. return base64;//返回Base64编码过的字节数组字符串
  52. } catch (IOException e) {
  53. e.printStackTrace();
  54. throw new Exception("图片上传失败,请联系客服!");
  55. }
  56. }