1、maven依赖
<!--zxing依赖-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.1.0</version>
</dependency>
2、一些重要属性方法
BarcodeFormat (码类型)
设置生成条形码的类型。
如:二维码、EAN-13码、UPC-A码、Code-128码、Code-39码等等。
条形码类型 |
BarcodeFormat.AZTEC 阿兹特克码 |
BarcodeFormat.CODABAR Codabar码 |
BarcodeFormat.CODE_39 CODE-30码 |
BarcodeFormat.CODE_93 CODE-93码 |
BarcodeFormat.CODE_128 CODE-128码 |
BarcodeFormat.DATA_MATRIX 矩阵式二维条码 |
BarcodeFormat.EAN_8 EAN-8码 |
BarcodeFormat.EAN_13 EAN-13码 |
BarcodeFormat.ITF 交插二五条码 |
BarcodeFormat.MAXICODE MaxiCode二维条码 |
BarcodeFormat.PDF_417 PDF417 |
BarcodeFormat.QR_CODE 二维码 |
BarcodeFormat.RSS_14 RSS 14 |
BarcodeFormat.RSS_EXPANDED RSS EXPANDED |
BarcodeFormat.UPC_A UPC A |
BarcodeFormat.UPC_E UPC E |
BarcodeFormat.UPC_EAN_EXTENSION UPC EAN EXTENSION |
EncodeHintType(自定义属性)
3、带logo得到二维码生成
/**
* @description: 二维码生成
* @author: HK
* @since: 2024/11/4 10:16
*/
public class Test3 {
private static final Integer CODE_WIDTH = 300; // 基础属性:二维码宽度,单位像素
private static final Integer CODE_HEIGHT = 300; // 基础属性:二维码高度,单位像素
private static final Integer FRONT_COLOR = 0x000000; // 基础属性:二维码前景色,0x000000 表示黑色
private static final Integer BACKGROUND_COLOR = 0xFFFFFF; // 基础属性:二维码背景色,0xFFFFFF 表示白色
public static void main(String[] args) throws Exception {
//设置生成二维码的内容
String qrMessage = "https://www.baidu.com";
// EncodeHintType:编码提示类型,枚举类型
// EncodeHintType.CHARACTER_SET:设置字符编码类型
// EncodeHintType.ERROR_CORRECTION:设置误差校正
// ErrorCorrectionLevel:误差校正等级,
// L = ~7% correction、M = ~15% correction、
// Q = ~25% correction、H = ~30% correction
// 不设置时,默认为 L 等级,等级不一样,生成的图案不同,但扫描的结果是一样的
// EncodeHintType.MARGIN:设置二维码边距,单位像素,值越小,二维码距离四周越近
Map<EncodeHintType, Object> typeObjectHashMap = new HashMap<EncodeHintType, Object>();
typeObjectHashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
typeObjectHashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
typeObjectHashMap.put(EncodeHintType.MARGIN, 1);
// MultiFormatWriter:多格式写入,这是一个工厂类,里面重载了两个 encode 方法,用于写入条形码或二维码
// encode(String contents,BarcodeFormat format,int width, int height,Map<EncodeHintType,?> hints)
// 参数1:contents:条形码/二维码内容
// 参数2:format:编码类型,如 条形码,二维码 等
// 参数3:width:码的宽度
// 参数4:height:码的高度