二维码(QRCode)在生活中已经是非常的常见,生成的方式也有很多种,本实例以zxing(3.3.2)为例,来演示二维码(QRCode)的生成和读取。

演示效果

先来看看效果:

Note:zxing除了生成二维码,还可以生成例如条形码等等。

POM.xml配置

本实例采用maven构建,所以在pom.xml中添加依赖jar包

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
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.devnp</groupId>
<artifactId>zxing-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>

<dependencies>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.2</version>
</dependency>

<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.2</version>
</dependency>

<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

</dependencies>

</project>

Java Code

a. zxing生成code

GenerateQRCode.java

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
package com.devnp.qrcode;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.datamatrix.DataMatrixReader;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.jvm.hotspot.utilities.BitMap;

import javax.imageio.ImageIO;
import javax.print.DocFlavor;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
* @author duliu
*/
public class GenerateQRCode {


/**
* 生成最基本的二维码
* @param text
* @param width
* @param height
* @param filePath
* @throws WriterException
* @throws IOException
*/
public static void generateImage(String text, int width, int height, String filePath) throws WriterException, IOException {

QRCodeWriter qrCodeWriter = new QRCodeWriter();

BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

Path path = FileSystems.getDefault().getPath(filePath);

MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

}

/**
* 生成带有参数的二维码
* @param text
* @param width
* @param height
* @param filePath
* @throws WriterException
* @throws IOException
*/
public static void encodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {

Path path = FileSystems.getDefault().getPath(filePath);

MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

Map<EncodeHintType, Object> map = new HashMap<>();

map.put(EncodeHintType.CHARACTER_SET, "utf-8"); //设置字符集
map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); //设置纠错等级
map.put(EncodeHintType.MARGIN, 2); //设置边距

BitMatrix bitMatrix = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, width, height, map) ;

MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}

/**
* 生成带有logo的二维码
* @param icoPath
* @param text
* @param width
* @param height
* @param filePath
* @throws WriterException
* @throws IOException
*/
public static void generateIcoImage(String icoPath, String text, int width, int height, String filePath) throws WriterException, IOException {

QRCodeWriter qrCodeWriter = new QRCodeWriter();

Map<EncodeHintType, Object> map = new HashMap<>();

map.put(EncodeHintType.CHARACTER_SET, "utf-8"); //设置字符集
map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //设置纠错等级
map.put(EncodeHintType.MARGIN, 1); //设置边距

BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, map);

BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

int qrHeight = qrImage.getHeight();
int qrWidth = qrImage.getWidth();

BufferedImage logoImage = adjustSize(qrHeight, qrWidth, icoPath);

//初始化新的二维码的生成
BufferedImage combined = new BufferedImage(qrImage.getHeight(), qrImage.getWidth(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) combined.getGraphics();

//画新的图片
g2d.drawImage(qrImage, 0, 0, null);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));

g2d.drawImage(logoImage, (int) Math.round((qrWidth -logoImage.getWidth())/2), (int) Math.round((qrHeight-logoImage.getHeight())/2), null);

//
ImageIO.write(combined, "png", new File(filePath));
}

public static BufferedImage adjustSize(int qrHeight, int qrWidth, String logoPath) throws IOException {
//读取LOGO ICO
File file = new File(logoPath);

BufferedImage logoImage = ImageIO.read(file);

//对logo进行缩放 将logo的大小设置为整个图片的1/5
int icoHeight = qrHeight / 5 ;
int icoWidth = qrWidth / 5 ;

BufferedImage newLogoImage = new BufferedImage(icoWidth, icoHeight,logoImage.getType());
Graphics g = newLogoImage.getGraphics();
g.drawImage(logoImage, 0,0,icoWidth, icoHeight,null);

g.dispose();

return newLogoImage ;
}

}

b. zxing读取code

ReaderQRCode.java

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
package com.devnp.qrcode;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
* @author duliu
*/
public class ReaderQRCode {

/**
* 读取二维码的信息
* @param filePath
* @return
* @throws FormatException
* @throws ChecksumException
* @throws NotFoundException
* @throws IOException
*/
public static String readImage(String filePath) throws FormatException, ChecksumException, NotFoundException, IOException {

BufferedImage bufferedImage = ImageIO.read(new File(filePath));

LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);

Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap bitmap = new BinaryBitmap(binarizer);

QRCodeReader qrCodeReader = new QRCodeReader();

Result result = qrCodeReader.decode(bitmap);

return result.getText() ;

}
}

c.测试code
GenerateQRCodeTest.java

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
package com.devnp.qrcode.test;


import com.devnp.qrcode.GenerateQRCode;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.WriterException;
import org.junit.Test;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class GenerateQRCodeTest {

@Test
public void generateImageTest() throws IOException, WriterException {
GenerateQRCode.generateImage("www.devnp.com", 60, 60, "simpleqrcode.png");
}

@Test
public void encodeImageTest() throws IOException, WriterException {
GenerateQRCode.encodeImage("www.devnp.com", 60, 60, "noramlqrcode.png");
}

@Test
public void generateIcoImage() throws IOException, WriterException {
GenerateQRCode.generateIcoImage("a476a0d05b33f3d9b76a780c9bd31d0f.jpeg","www.devnp.com", 120, 120, "qricocode.png");
}

@Test
public void adjustSizeTest() throws IOException {
BufferedImage bufferedImages = GenerateQRCode.adjustSize(120, 120, "a476a0d05b33f3d9b76a780c9bd31d0f.jpeg");

ImageIO.write(bufferedImages, "png", new File("logo.png"));
}

}

ReaderQRCodeTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.devnp.qrcode.test;

import com.devnp.qrcode.GenerateQRCode;
import com.devnp.qrcode.ReaderQRCode;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import org.junit.Test;

import java.io.IOException;

public class ReaderQRCodeTest {

@Test
public void readImageTest() throws IOException, ChecksumException, NotFoundException, FormatException {
String content = ReaderQRCode.readImage("qrcode.png");

System.out.println(content);
}
}

3,代码下载

zxing-demo.zip