介绍
BarcodeUtils是基于Google提供的zxing二维码生成库而整合的一个生成或者解析条形码的工具类。BarcodeUtils采用遵循COC原则,在调用者未声明生成配置时,默认生成编码为UTF-8,尺寸为180*70的条形码,默认图片格式为png。
引入依赖
<!--> google zxing <-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
<!--> thumbnailator <-->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
核心代码
package org.oriboy.qrcode;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.EnumMap;
import java.util.Map;
/**
* 条形码生成/解析工具类
* @author rocky
* @date 2021/3/18 15:25
*/
public class BarcodeUtils {
/**
* 条形码默认宽度
*/
private static final int BARCODE_WIDTH = 180;
/**
* 条形默认高度
*/
private static final int BARCODE_HEIGHT = 70;
/**
* 默认条形码文件格式
*/
private static final String FORMAT = "png";
/**
* 条形条形码参数
*/
private static final EnumMap<EncodeHintType, Object> ENCODE_HINTS = new EnumMap<>(EncodeHintType.class);
/**
* 解析条形码参数
*/
private static final EnumMap<DecodeHintType, Object> DECODE_HINTS = new EnumMap<>(DecodeHintType.