ImageUtils.java 2.6 KB

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