GeXiangDong

精通Java、SQL、Spring的拼写,擅长Linux、Windows的开关机

0%

用google ZXing生成二维码、一维码的小例子

用google ZXing生成二维码、一维码的小例子

pom 依赖

增加依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>

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
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.FileOutputStream;
import java.util.Hashtable;

/**
* 创建二维码、一维码的例子
*/
public class Qrcode {

public static void main(String[] args) throws Exception {
createBarCode("012341");
createQrCode("http://www.163.com");
}

/**
* 创建二维码
* @param content
* @throws Exception
*/
private static void createQrCode(String content) throws Exception{
String format = "png";
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%)
hints.put(EncodeHintType.MARGIN, 10);
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 300, 300, hints);

FileOutputStream fos = new FileOutputStream("target/qrcode.png");
MatrixToImageWriter.writeToStream(bitMatrix, format, fos);
fos.close();
}



/**
* 一维条码
* @param text
* @throws Exception
*/
private static void createBarCode(String text) throws Exception{
String format = "png";
Hashtable hints= new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

String content = "http://www.163.com";
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, 300, 80, hints);

FileOutputStream fos = new FileOutputStream("target/barcode.png");
MatrixToImageWriter.writeToStream(bitMatrix, format, fos);
fos.close();
}
}