imageUtils.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package com.template.common.utils;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.util.Base64;
  8. /**
  9. * @Author: binguo
  10. * @Date: 2024/1/9 星期二 15:17
  11. * @Description: com.template.common.utils
  12. * @Version: 1.0
  13. */
  14. public class imageUtils {
  15. public static String getBase64Url(String imagePath){
  16. ByteArrayOutputStream outPut = new ByteArrayOutputStream();
  17. byte[] data = new byte[1024];
  18. try {
  19. // 创建URL
  20. URL url = new URL(imagePath);
  21. // 创建链接
  22. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  23. conn.setRequestMethod("GET");
  24. conn.setConnectTimeout(10 * 1000);
  25. if(conn.getResponseCode() != 200) {
  26. return "fail";//连接失败/链接失效/图片不存在
  27. }
  28. InputStream inStream = conn.getInputStream();
  29. int len = -1;
  30. while ((len = inStream.read(data)) != -1) {
  31. outPut.write(data, 0, len);
  32. }
  33. inStream.close();
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. }
  37. // 对字节数组Base64编码
  38. byte[] encode = Base64.getEncoder().encode(outPut.toByteArray());
  39. String res = new String(encode);
  40. return res;
  41. }
  42. //https://www.jb51.net/program/288342ppk.htm 图片压缩大小
  43. }