ImageUtils.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package com.ruoyi.common.utils.file;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.FileInputStream;
  5. import java.io.InputStream;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8. import java.util.Arrays;
  9. import org.apache.poi.util.IOUtils;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import com.ruoyi.common.config.RuoYiConfig;
  13. import com.ruoyi.common.constant.Constants;
  14. import com.ruoyi.common.utils.StringUtils;
  15. /**
  16. * 图片处理工具类
  17. *
  18. * @author ruoyi
  19. */
  20. public class ImageUtils
  21. {
  22. private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);
  23. public static byte[] getImage(String imagePath)
  24. {
  25. InputStream is = getFile(imagePath);
  26. try
  27. {
  28. return IOUtils.toByteArray(is);
  29. }
  30. catch (Exception e)
  31. {
  32. log.error("图片加载异常 {}", e);
  33. return null;
  34. }
  35. finally
  36. {
  37. IOUtils.closeQuietly(is);
  38. }
  39. }
  40. public static InputStream getFile(String imagePath)
  41. {
  42. try
  43. {
  44. byte[] result = readFile(imagePath);
  45. result = Arrays.copyOf(result, result.length);
  46. return new ByteArrayInputStream(result);
  47. }
  48. catch (Exception e)
  49. {
  50. log.error("获取图片异常 {}", e);
  51. }
  52. return null;
  53. }
  54. /**
  55. * 读取文件为字节数据
  56. *
  57. * @param key 地址
  58. * @return 字节数据
  59. */
  60. public static byte[] readFile(String url)
  61. {
  62. InputStream in = null;
  63. ByteArrayOutputStream baos = null;
  64. try
  65. {
  66. if (url.startsWith("http"))
  67. {
  68. // 网络地址
  69. URL urlObj = new URL(url);
  70. URLConnection urlConnection = urlObj.openConnection();
  71. urlConnection.setConnectTimeout(30 * 1000);
  72. urlConnection.setReadTimeout(60 * 1000);
  73. urlConnection.setDoInput(true);
  74. in = urlConnection.getInputStream();
  75. }
  76. else
  77. {
  78. // 本机地址
  79. String localPath = RuoYiConfig.getProfile();
  80. String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
  81. in = new FileInputStream(downloadPath);
  82. }
  83. return IOUtils.toByteArray(in);
  84. }
  85. catch (Exception e)
  86. {
  87. log.error("获取文件路径异常 {}", e);
  88. return null;
  89. }
  90. finally
  91. {
  92. IOUtils.closeQuietly(in);
  93. IOUtils.closeQuietly(baos);
  94. }
  95. }
  96. }