E1ED922C1E9526DD63272D7EC5C6CB77
2020-09-27 89ac7f9b30215669a15fb4fec39d698cb1892c6d
提交 | 用户 | age
5c5945 1 package com.hx.util;
E 2
3 import java.awt.*;
4 import java.awt.image.BufferedImage;
5 import java.io.File;
6 import java.io.IOException;
7 import java.text.SimpleDateFormat;
8 import java.util.*;
9 import java.util.List;
10
11 import javax.imageio.ImageIO;
12
13 import com.google.zxing.*;
14
15 import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
16 import com.google.zxing.common.BitMatrix;
17 import com.google.zxing.common.HybridBinarizer;
18 import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
19
20 public class QRCodeUtil {
21
22     // 二维码颜色==黑色
23     private static final int BLACK = 0xFF000000;
24     // 二维码颜色==白色
25     private static final int WHITE = 0xFFFFFFFF;
26     // 二维码图片格式==jpg和png两种
27     private static final List<String> IMAGE_TYPE = new ArrayList<>();
28
29     static {
30         IMAGE_TYPE.add("jpg");
31         IMAGE_TYPE.add("png");
32     }
33
34     /**
35      * zxing方式生成二维码
36      * 注意:
37      * 1,文本生成二维码的方法独立出来,返回image流的形式,可以输出到页面
38      * 2,设置容错率为最高,一般容错率越高,图片越不清晰, 但是只有将容错率设置高一点才能兼容logo图片
39      * 3,logo图片默认占二维码图片的20%,设置太大会导致无法解析
40      *
41      * @param content  二维码包含的内容,文本或网址
42      * @param path     生成的二维码图片存放位置
43      * @param size     生成的二维码图片尺寸 可以自定义或者默认(250)
44      * @param logoPath logo的存放位置
45      * @param autoDateFolder 在存放链接上生成日期文件夹,格式是yyyyMM
46      */
47     public static String QRCodeCreate(String content, String path, Integer size, String logoPath,Boolean autoDateFolder) {
48         try {
49             Date newDate = new Date();
50             if(autoDateFolder){
51                 if(autoDateFolder){
52                     if(path.endsWith("/")){
53                         path = path+dateFormat(newDate,"yyyyMM")+"/";
54                     }else{
55                         path = path+"/"+dateFormat(newDate,"yyyyMM")+"/";
56                     }
57                 }
58             }
59
60             path = path+newDate.getTime()+".jpg";
61
62             //图片类型
63             String imageType = "jpg";
64             //获取二维码流的形式,写入到目录文件中
65             BufferedImage image = getBufferedImage(content, size, logoPath);
66             //获得随机数
67             Random random = new Random();
68             //生成二维码存放文件
69             File file = new File(path);
70             if (!file.exists()) {
71                 file.mkdirs();
72             }
73             ImageIO.write(image, imageType, file);
74         } catch (IOException e) {
75             e.printStackTrace();
76         }
77         return path;
78     }
79
80     /**
81      * 二维码流的形式,包含文本内容
82      *
83      * @param content  二维码文本内容
84      * @param size     二维码尺寸
85      * @param logoPath logo的存放位置
86      * @return
87      */
88     public static BufferedImage getBufferedImage(String content, Integer size, String logoPath) {
89         if (size == null || size <= 0) {
90             size = 250;
91         }
92         BufferedImage image = null;
93         try {
94             // 设置编码字符集
95             Map<EncodeHintType, Object> hints = new HashMap<>();
96             //设置编码
97             hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
98             //设置容错率最高
99             hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
100             hints.put(EncodeHintType.MARGIN, 1);
101             // 1、生成二维码
102             MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
103             BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, size, size, hints);
104             // 2、获取二维码宽高
105             int codeWidth = bitMatrix.getWidth();
106             int codeHeight = bitMatrix.getHeight();
107             // 3、将二维码放入缓冲流
108             image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
109             for (int i = 0; i < codeWidth; i++) {
110                 for (int j = 0; j < codeHeight; j++) {
111                     // 4、循环将二维码内容定入图片
112                     image.setRGB(i, j, bitMatrix.get(i, j) ? BLACK : WHITE);
113                 }
114             }
115             //判断是否写入logo图片
116             if (logoPath != null && !"".equals(logoPath)) {
117                 File logoPic = new File(logoPath);
118                 if (logoPic.exists()) {
119                     Graphics2D g = image.createGraphics();
120                     BufferedImage logo = ImageIO.read(logoPic);
121                     int widthLogo = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image.getWidth() * 2 / 10) : logo.getWidth(null);
122                     int heightLogo = logo.getHeight(null) > image.getHeight() * 2 / 10 ? (image.getHeight() * 2 / 10) : logo.getHeight(null);
123                     int x = (image.getWidth() - widthLogo) / 2;
124                     int y = (image.getHeight() - heightLogo) / 2;
125                     // 开始绘制图片
126                     g.drawImage(logo, x, y, widthLogo, heightLogo, null);
127                     g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
128                     //边框宽度
129                     g.setStroke(new BasicStroke(2));
130                     //边框颜色
131                     g.setColor(Color.WHITE);
132                     g.drawRect(x, y, widthLogo, heightLogo);
133                     g.dispose();
134                     logo.flush();
135                     image.flush();
136                 }
137             }
138         } catch (WriterException e) {
139             e.printStackTrace();
140         } catch (IOException e) {
141             e.printStackTrace();
142         }
143         return image;
144     }
145
146     /**
147      * 给二维码图片添加Logo
148      *
149      * @param qrPic   二维码图片
150      * @param logoPic logo图片
151      * @param path    合成后的图片存储目录
152      */
153     public static boolean zxingCodeCreate(File qrPic, File logoPic, String path) {
154         try {
155             String imageType = path.substring(path.lastIndexOf(".") + 1).toLowerCase();
156             if (!IMAGE_TYPE.contains(imageType)) {
157                 return false;
158             }
159
160             if (!qrPic.isFile() && !logoPic.isFile()) {
161                 return false;
162             }
163
164             //读取二维码图片,并构建绘图对象
165             BufferedImage image = ImageIO.read(qrPic);
166             Graphics2D g = image.createGraphics();
167             //读取Logo图片
168             BufferedImage logo = ImageIO.read(logoPic);
169             //设置logo的大小,最多20%0
170             int widthLogo = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image.getWidth() * 2 / 10) : logo.getWidth(null);
171             int heightLogo = logo.getHeight(null) > image.getHeight() * 2 / 10 ? (image.getHeight() * 2 / 10) : logo.getHeight(null);
172             // 计算图片放置位置,默认在中间
173             int x = (image.getWidth() - widthLogo) / 2;
174             int y = (image.getHeight() - heightLogo) / 2;
175             // 开始绘制图片
176             g.drawImage(logo, x, y, widthLogo, heightLogo, null);
177             g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
178             //边框宽度
179             g.setStroke(new BasicStroke(2));
180             //边框颜色
181             g.setColor(Color.WHITE);
182             g.drawRect(x, y, widthLogo, heightLogo);
183             g.dispose();
184             logo.flush();
185             image.flush();
186             File newFile = new File(path);
187             if (!newFile.exists()) {
188                 newFile.mkdirs();
189             }
190             ImageIO.write(image, imageType, newFile);
191             return true;
192         } catch (Exception e) {
193             e.printStackTrace();
194             return false;
195         }
196     }
197
198
199     /**
200      * 二维码的解析方法
201      *
202      * @param path 二维码图片目录
203      * @return
204      */
205     public static Result zxingCodeAnalyze(String path) {
206         try {
207             MultiFormatReader formatReader = new MultiFormatReader();
208             File file = new File(path);
209             if (file.exists()) {
210                 BufferedImage image = ImageIO.read(file);
211                 LuminanceSource source = new BufferedImageLuminanceSource(image);
212                 Binarizer binarizer = new HybridBinarizer(source);
213                 BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
214                 Map hints = new HashMap();
215                 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
216                 Result result = formatReader.decode(binaryBitmap, hints);
217                 return result;
218             }
219         } catch (IOException e) {
220             e.printStackTrace();
221         } catch (NotFoundException e) {
222             e.printStackTrace();
223         }
224         return null;
225     }
226
227     /**
228      *
229      * @param date 时间
230      * @param format 时间格式
231      * @return 返回的时间格式字符串
232      */
233     public static String dateFormat(Date  date,String format) {
234         SimpleDateFormat df = new SimpleDateFormat(format);//设置日期格式
235         return df.format(date);
236     }
237
238 }