Spring Boot集成zxing实现生成二维码功能

1.二维码介绍

二维码QR Code(Quick Response Code)

由Denso公司于1994年9月研制的一种矩阵二维码符号,它具有一维条码及其它二维条码所具有的信息容量大、可靠性高、可表示汉字及图象多种文字信息、保密防伪性强等优点。

 ZXing

一个支持在图像中解码和生成条形码(如二维码、PDF 417、EAN、UPC、Aztec、Data Matrix、Codabar)的库。ZXing(“zebra crossing”)是一个开源的、多格式的、用Java实现的一维/二维条码图像处理库,具有到其他语言的端口。

2.代码功能

 pom.xml

    
<?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">    <parent>        <artifactId>springboot-demo</artifactId>        <groupId>com.et</groupId>        <version>1.0-SNAPSHOT</version>    </parent>    <modelVersion>4.0.0</modelVersion>
<artifactId>qrcode</artifactId>
<properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.5.15</version> </dependency> </dependencies></project>

applicatio.yaml

    
server:  port: 8088

QRCodeGenerator.java

    
package com.et.qrcode.util;
import com.google.zxing.BarcodeFormat;import com.google.zxing.WriterException;import com.google.zxing.client.j2se.MatrixToImageWriter;import com.google.zxing.common.BitMatrix;import com.google.zxing.qrcode.QRCodeWriter;
import java.io.ByteArrayOutputStream;import java.io.IOException;import java.nio.file.FileSystems;import java.nio.file.Path;import java.util.Base64;
/** * QRCodeGenerator * * @author zhouzhaodong */public class QRCodeGenerator {
/** * generateQRCodeImage * @param text * @param width * @param height * @param filePath * @throws WriterException * @throws IOException */ public static void generateQRCodeImage(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); }
/** * writeToStream * @param text * @param width * @param height * @return */ public static String writeToStream(String text, int width, int height) { String message = ""; QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix; try { bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream); Base64.Encoder encoder = Base64.getEncoder(); message = encoder.encodeToString(outputStream.toByteArray()); } catch (Exception e) { e.printStackTrace(); } return message; }
}

Controller

    
package com.et.qrcode.controller;
import cn.hutool.core.io.FileUtil;import cn.hutool.extra.qrcode.QrCodeUtil;import cn.hutool.extra.qrcode.QrConfig;import com.et.qrcode.util.QRCodeGenerator;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;
import java.awt.*;
/** * generate qrcode * @author zhouzhaodong */@Controllerpublic class QRCodeController {
/** * qrcodeImage * @param orderNo * @return */ @RequestMapping("/original/qrcode/image") public String qrcodeImage(String orderNo) { String failPath = "D:\\tmp\\" + orderNo + ".png"; try { QRCodeGenerator.generateQRCodeImage(orderNo, 350, 350, failPath); } catch (Exception e) { e.printStackTrace(); } return failPath; }
/** * qrcodeBase64 * @param orderNo * @return */ @RequestMapping("/original/qrcode/base64") public String qrcodeBase64(String orderNo) { String message = ""; try { message = QRCodeGenerator.writeToStream(orderNo, 350, 350); } catch (Exception e) { e.printStackTrace(); } return message; }

@RequestMapping("/hblog/qrcode/image1") public String hutoolsImages1() { String message = ""; try { QrConfig config = new QrConfig(300, 300); // Set the margin, that is, the margin between the QR code and the background config.setMargin(3); // Set the foreground color, which is the QR code color (cyan) config.setForeColor(Color.CYAN.getRGB()); // Set background color (gray) config.setBackColor(Color.GRAY.getRGB()); // Generate QR code to file or stream QrCodeUtil.generate("http://www.liuhiahua.cn/", config, FileUtil.file("D:\\tmp\\hblog1.png")); } catch (Exception e) { e.printStackTrace(); } return message; }
@RequestMapping("/hblog/qrcode/image2") public String hutoolsImages2() { String message = ""; try { QrCodeUtil.generate(// "http://www.liuhiahua.cn/", //content QrConfig.create().setImg("D:\\tmp\\logo.png"), //logo FileUtil.file("D:\\tmp\\qrcodeWithLogo.jpg")//output file ); } catch (Exception e) { e.printStackTrace(); } return message; }
}

DemoApplication.java

    
package com.et.qrcode;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplicationpublic class DemoApplication {
public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}

代码仓库

  • https://github.com/Harries/springboot-demo

3.测试

原始zxing生成qrcode

访问http://127.0.0.1:8088/original/qrcode/image?orderNo=222,查看目录下生成的文件

采用hutool生成qrcode

访问http://127.0.0.1:8088//hblog/qrcode/image2,查看文件

生成带有logo的二维码

访问http://127.0.0.1:8088//hblog/qrcode/image1,查看文件

4.引用

  • https://www.bookstack.cn/read/hutool/18a69dd68fd334c8.md

  • http://www.liuhaihua.cn/archives/710338.html

  • https://zxing.github.io/zxing/

相关推荐

  • Java日志系统历史从入门到崩溃
  • 几种常见的 Kafka 集群监控工具
  • 持续移动开发如何从测试自动化中获益
  • 大模型企业怎么“卷”过 | 直播预告
  • 把大模型装进手机,小米、OPPO、vivo 卷起来了!
  • Stable Diffusion核心团队全部离职!Kimi大面积宕机,月之暗面已扩容5次;Redis不再“开源”引争议 |Q资讯
  • 能玩3D游戏的AI玩家!谷歌新智能体SIMA发布,但水平还在“新手村”
  • 微软围着Copilot 转!首款AI PC能算惊艳吗?网友:9分钟宣传片让人昏昏欲睡
  • Redis“叛逃”开源,得罪了几乎所有人
  • 搭建一个符合大厂标准的Vue3+Ts +Vite脚手架
  • JS官方宣布:通过了groupBy方法的提案!开发效率又提升了~
  • AI的大机会
  • Redis 不再开源??
  • JDK 22 发布正式版了
  • 华为某外包:名校毕业,自以为能力吊打华为16级以上员工,年薪总包却只有30万。网友:刚接触职场?自我感觉太良好了?
  • 浅聊一下最接近英伟达B200的AI芯片
  • 72岁法国概率论大佬获阿贝尔奖,陶哲轩:他的知名度理应更高
  • Kaggle竞赛赢得根本停不下来--Psi.
  • 每日 prompt:天空之岛🏝️
  • Stable Diffusion核心团队全离职,微软6.5亿收购Inflection AI