春风项目四线(合箱线、总装线)
yyt
2024-02-17 f7a99591d83efd59af37b257e30d12f10291f4ef
提交 | 用户 | 时间
fd2207 1 package com.jcdm.common.utils.file;
2
3 import java.io.ByteArrayInputStream;
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.jcdm.common.config.MesConfig;
13 import com.jcdm.common.constant.Constants;
14 import com.jcdm.common.utils.StringUtils;
15
16 /**
17  * 图片处理工具类
18  *
19  * @author jc
20  */
21 public class ImageUtils
22 {
23     private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);
24
25     public static byte[] getImage(String imagePath)
26     {
27         InputStream is = getFile(imagePath);
28         try
29         {
30             return IOUtils.toByteArray(is);
31         }
32         catch (Exception e)
33         {
34             log.error("图片加载异常 {}", e);
35             return null;
36         }
37         finally
38         {
39             IOUtils.closeQuietly(is);
40         }
41     }
42
43     public static InputStream getFile(String imagePath)
44     {
45         try
46         {
47             byte[] result = readFile(imagePath);
48             result = Arrays.copyOf(result, result.length);
49             return new ByteArrayInputStream(result);
50         }
51         catch (Exception e)
52         {
53             log.error("获取图片异常 {}", e);
54         }
55         return null;
56     }
57
58     /**
59      * 读取文件为字节数据
60      * 
61      * @param url 地址
62      * @return 字节数据
63      */
64     public static byte[] readFile(String url)
65     {
66         InputStream in = null;
67         try
68         {
69             if (url.startsWith("http"))
70             {
71                 // 网络地址
72                 URL urlObj = new URL(url);
73                 URLConnection urlConnection = urlObj.openConnection();
74                 urlConnection.setConnectTimeout(30 * 1000);
75                 urlConnection.setReadTimeout(60 * 1000);
76                 urlConnection.setDoInput(true);
77                 in = urlConnection.getInputStream();
78             }
79             else
80             {
81                 // 本机地址
82                 String localPath = MesConfig.getProfile();
83                 String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
84                 in = new FileInputStream(downloadPath);
85             }
86             return IOUtils.toByteArray(in);
87         }
88         catch (Exception e)
89         {
90             log.error("获取文件路径异常 {}", e);
91             return null;
92         }
93         finally
94         {
95             IOUtils.closeQuietly(in);
96         }
97     }
98 }