ZQN
2024-08-14 f6a1bf1d9b19dd8b3750034048f3876d086db1f1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package com.project.common.utils.file;
 
import com.alibaba.fastjson2.JSONObject;
import com.google.zxing.WriterException;
import com.project.common.config.ProjectConfig;
import com.project.common.constant.Constants;
import com.project.common.utils.StringUtils;
import com.project.common.utils.WeChatUtils;
import com.project.common.utils.qrcode.QRCodeUtil;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
 
import static com.project.common.utils.file.FileUploadUtils.getPathFileName;
 
/**
 * 图片处理工具类
 *
 * @author project
 */
public class ImageUtils
{
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);
 
    public static byte[] getImage(String imagePath)
    {
        InputStream is = getFile(imagePath);
        try
        {
            return IOUtils.toByteArray(is);
        }
        catch (Exception e)
        {
            log.error("图片加载异常 {}", e);
            return null;
        }
        finally
        {
            IOUtils.closeQuietly(is);
        }
    }
 
    public static InputStream getFile(String imagePath)
    {
        try
        {
            byte[] result = readFile(imagePath);
            result = Arrays.copyOf(result, result.length);
            return new ByteArrayInputStream(result);
        }
        catch (Exception e)
        {
            log.error("获取图片异常 {}", e);
        }
        return null;
    }
 
    /**
     * 读取文件为字节数据
     *
     * @param url 地址
     * @return 字节数据
     */
    public static byte[] readFile(String url)
    {
        InputStream in = null;
        try
        {
            if (url.startsWith("http"))
            {
                // 网络地址
                URL urlObj = new URL(url);
                URLConnection urlConnection = urlObj.openConnection();
                urlConnection.setConnectTimeout(30 * 1000);
                urlConnection.setReadTimeout(60 * 1000);
                urlConnection.setDoInput(true);
                in = urlConnection.getInputStream();
            }
            else
            {
                // 本机地址
                String localPath = ProjectConfig.getProfile();
                String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
                in = new FileInputStream(downloadPath);
            }
            return IOUtils.toByteArray(in);
        }
        catch (Exception e)
        {
            log.error("获取文件路径异常 {}", e);
            return null;
        }
        finally
        {
            IOUtils.closeQuietly(in);
        }
    }
 
 
    /**
     *
     * @param content
     * @param type
     * @return
     * @throws WriterException
     * @throws IOException
     */
    public static String createQrcode(String content, String name, String type)
    {
        // 本地资源路径
        String localPath = ProjectConfig.getQrcodePath();
        String key = content + "-" + type;
        String fileName = key + ".png";
        File file = new File(localPath, fileName);
        if (!file.exists()){
            try {
                if (!file.createNewFile()) return "生成二维码文件失败!";
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
 
            if ("1".equals(type)){
                try {
                    String accessToken = WeChatUtils.getAccessToken();
                    URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    if (httpURLConnection instanceof HttpsURLConnection)  {
                        SSLContext sc = SSLContext.getInstance("SSL");
                        sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
                        ((HttpsURLConnection) httpURLConnection).setSSLSocketFactory(sc.getSocketFactory());
                        ((HttpsURLConnection) httpURLConnection).setHostnameVerifier(new TrustAnyHostnameVerifier());
                    }
 
                    // conn.setConnectTimeout(10000);//连接超时 单位毫秒
                    // conn.setReadTimeout(2000);//读取超时 单位毫秒
                    // 发送POST请求必须设置如下两行
                    httpURLConnection.setDoOutput(true); // 打开写入属性
                    httpURLConnection.setDoInput(true); // 打开读取属性
                    httpURLConnection.setRequestMethod("POST");// 提交方式
                    // 不得不说一下这个提交方式转换!!真的坑。。改了好长时间!!一定要记得加响应头
                    httpURLConnection.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");// 设置响应头
                    // 获取URLConnection对象对应的输出流
                    PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
                    // 发送请求参数
                    JSONObject paramJson = new JSONObject();
 
                    paramJson.put("check_path", false);
                    //跳转开发
//                    paramJson.put("env_version", "develop");
                    // 跳转体验
//                    paramJson.put("env_version", "trial");
                    //跳转正式
                    paramJson.put("env_version", "release");
 
                    paramJson.put("scene", content); // 你要放的内容
                    paramJson.put("path", "pages/index/index");
                    paramJson.put("width", 260); // 宽度
                    paramJson.put("auto_color", true);
                    printWriter.write(paramJson.toString());
                    // flush输出流的缓冲
                    printWriter.flush();
                    BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
 
                    OutputStream os = Files.newOutputStream(file.toPath());
                    int len;
                    byte[] arr = new byte[1024];
                    while ((len = bis.read(arr)) != -1) {
                        os.write(arr, 0, len);
                        os.flush();
                    }
                    os.close();
                    // 上传云储存
                    //InputStream is = new ByteArrayInputStream(os.toByteArray());
                    //retMap = UploadUtils
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            else if ("2".equals(type)){
                QRCodeUtil.contextLoads2(content,  name, file.getPath());
            }
 
        }
        try {
            return getPathFileName(localPath, fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
 
    }
 
    private static class TrustAnyTrustManager implements X509TrustManager {
 
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
 
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
 
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }
 
    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
 
 
    }
 
 
}