Springboot + zxing 生成二维码

1 引入依赖

<!-- 二维码相关 -->
<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>core</artifactId>
	<version>3.4.1</version>
</dependency>

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

2 生成二维码

try {
	// 二维码的宽高
	int width = 300;
	int height = 300;
	// 二维码内容
	String content = "这是一个测试二维码";
	// 二维码图片的格式
	String format = "png";
	// 定义二维码参数
	HashMap<EncodeHintType, Object> hints = new HashMap<>();
	// 字符编码
	hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
	//纠错等级,二维码受到污染后的识别准确度,自行了解后修改
	hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
	// 边距
	hints.put(EncodeHintType.MARGIN, 2);
	// 颜色设置(二维码颜色,图片背景颜色)
	MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(0xFF161B2A,0x00FFFFFF);
	BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
	// 二维码输出的路径
	Path file = new File("D:\\image\\img.png").toPath();
	// 将二维码进行输出
	MatrixToImageWriter.writeToPath(bitMatrix, format, file,matrixToImageConfig);
} catch (Exception e) {
	e.printStackTrace();
}

3 读取二维码

try {
	MultiFormatReader formatReader = new MultiFormatReader();
	File file = new File("D:\\image\\img.png");
	BufferedImage image = null;
	image = ImageIO.read(file);
	BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
	// 定义二维码的参数
	HashMap<DecodeHintType,Object> hints = new HashMap<>();
	hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
	Result result = formatReader.decode(binaryBitmap, hints);
	System.out.println("解析结果: " + result.toString());
	System.out.println("二维码格式类型:" + result.getBarcodeFormat());
	System.out.println("二维码文本内容:" + result.getText());
} catch (Exception e) {
	e.printStackTrace();
} 
posted @ 2024-04-13 16:12  鱼鱼寡欢  阅读(136)  评论(0编辑  收藏  举报