QRCodeUtil.java
3.11 KB
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
package com.glsx.usercenter.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import net.glxn.qrgen.QRCode;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.EnumMap;
import java.util.Map;
public class QRCodeUtil {
public static void generateQRCode(String codeTest, OutputStream os) {
int size = 250;
String fileType = "png";
try {
Map<EncodeHintType, Object> hintMap = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// Now with zxing version 3.2.1 you could change border size (white border size to just 1)
hintMap.put(EncodeHintType.MARGIN, 1); /* default = 4 */
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(codeTest, BarcodeFormat.QR_CODE, size, size, hintMap);
int crunchifyWidth = byteMatrix.getWidth();
int crunchifyHeight = byteMatrix.getHeight();
BufferedImage image = new BufferedImage(crunchifyWidth, crunchifyHeight, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, crunchifyWidth, crunchifyHeight);
graphics.setColor(Color.BLACK);
for (int i = 0; i < crunchifyWidth; i++) {
for (int j = 0; j < crunchifyHeight; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
ImageIO.write(image, fileType, os);
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 生产二维码字节数组
*
* @param content
* @return
*/
public static byte[] generateQRCodeBy(String content) {
ByteArrayOutputStream out = QRCode.from(content).withCharset("UTF-8").withSize(240, 240).stream();
return out.toByteArray();
}
/**
* 根据二维码内容获取相关二维码流
*
* @param content
* @return
*/
public static ByteArrayInputStream getQRCode(String content) {
ByteArrayInputStream bin = null;
ByteArrayOutputStream bout = QRCode.from(content).withCharset("UTF-8").withSize(240, 240).stream();
byte buf[] = new byte[2048];
buf = bout.toByteArray();
bin = new ByteArrayInputStream(buf);
return bin;
}
public static void main(String[] args) throws IOException, WriterException {
}
}