package com.project.common.utils.file; 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 com.alibaba.fastjson2.JSONObject; import com.project.common.config.ProjectConfig; import com.project.common.utils.WeChatUtils; import com.project.common.utils.qrcode.QRCodeUtil; import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import org.apache.poi.util.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.project.common.constant.Constants; import com.project.common.utils.StringUtils; import javax.net.ssl.*; 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 Object createQrcode(String content, 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)){ try { String destPath = localPath+"/logo.png"; QRCodeUtil.encode(content, destPath, file.getPath(),true); } catch (IOException | WriterException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } 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; } } }