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

news2024/9/27 15:34:41

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
 */
@Controller
public 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;


@SpringBootApplication
public 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,查看目录下生成的文件17b1c8af765cb8c90e0bad4a7bfca096.png

采用hutool生成qrcode

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

生成带有logo的二维码

访问http://127.0.0.1:8088//hblog/qrcode/image1,查看文件1197ede0b43e82700e41c6ac67d9351b.jpeg

4.引用

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

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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1541875.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

项目1-加法计算器

1.创建项目 2.导入前端代码 2.1 static包内 2.2 测试前端代码是否有误 显示成功说明无误 2.3 定义用户接口 请求路径&#xff1a;calc/sum 请求方式&#xff1a;GET/POST 接口描述&#xff1a;计算两个整数相加 请求参数: 参数名类型是否必须备注num1Integer是参与计算的第…

代码随想录算法训练营Day56 ||leetCode 583. 两个字符串的删除操作 || 72. 编辑距离

647. 回文子串 dp[i][j]表示第i位开始&#xff0c;第j位结束的字符串是否为回文串 class Solution { public:int countSubstrings(string s) {vector<vector<bool>> dp(s.size(), vector<bool>(s.size(), false));int result 0;for (int i s.size() - 1…

【WEEK4】 【DAY5】AJAX - Part Two【English Version】

2024.3.22 Friday Following the previous article 【WEEK4】 【DAY4】AJAX - Part One【English Version】 Contents 8.4. Ajax Asynchronous Data Loading8.4.1. Create User.java8.4.2. Add lombok and jackson support in pom.xml8.4.3. Change Tomcat Settings8.4.4. Mo…

深入探索C语言动态内存分配:释放你的程序潜力

&#x1f308;大家好&#xff01;我是Kevin&#xff0c;蠢蠢大一幼崽&#xff0c;很高兴你们可以来阅读我的博客&#xff01; &#x1f31f;我热衷于分享&#x1f58a;学习经验&#xff0c;&#x1f3eb;多彩生活&#xff0c;精彩足球赛事⚽ &#x1f31f;感谢大家的支持&#…

Rust egui(3) 增加多个tab

话说不知道咋写&#xff0c;要不直接上git patch吧。代码都是移植的官方demo&#xff0c;核心改动就是把原来的line_demo换成了plot_demo&#xff0c;里面实现多个ui&#xff0c;然后点击tab标题会切换不同的ui。 如下图&#xff0c;Lines和Markers两个不同的标签对应不同的ui。…

基于Google云原生工程师的kubernetes最佳实践(二)

目录 二、应用部署篇 为deployment打上丰富的label,以便selecting 使用sidecar容器部署agent、proxy等组件 使用init container处理依赖关系,而不要用sidecar 镜像tag使用版本号,不要用latest或空tag 为pod设置readiness和liveness探针 不要给所有服务都使用LoadBalance…

eNSP实验一(静态)

目录 命名更改 子网划分 配置IP DHCP配置 配置静态路由 NET设置 Telnet及端口映射 浮动静态路由 命名更改 <Huawei>system-view Enter system view, return user view with CtrlZ. [Huawei]sysname R1 [R1] 1、R6为ISP&#xff0c;接口IP地址均为公有地址(12.0…

RuleApp资源社区,知识付费社区,可对接typecho的小程序APP

强大的文章/社区/自媒体客户端&#xff0c;支持打包为安卓&#xff0c;苹果&#xff0c;小程序。包括文章模块&#xff0c;用户模块&#xff0c;支付模块&#xff0c;聊天模块&#xff0c;商城模块等基础功能&#xff0c;包含VIP会员&#xff0c;付费阅读等收费体系&#xff0c…

蓝桥杯第十五届抱佛脚(二)竞赛中的数据结构

蓝桥杯第十五届抱佛脚&#xff08;二&#xff09;内置数据结构 文章目录 蓝桥杯第十五届抱佛脚&#xff08;二&#xff09;内置数据结构在竞赛中常见的数据结构数组(Array)链表(Linked List)栈(Stack)队列(Queue)树(Tree)映射(Map) 内置数据结构的快速使用迭代器&#xff08;It…

stm32知识总结--简单复习各部件

目录 内部结构 部件介绍 配置步骤 之前学了很多部件&#xff0c;配置了很多参数&#xff0c;但是没有很系统地把他们连接在一起&#xff0c;今天这个图里简洁描述了资源与资源之间的关系。 内部结构 部件介绍 黑框部分为CPU、内部有一个内核专门处理事件&#xff0c;所有的…

【Node.js】zlib

gzip 和 deflate 的基本使用 const zlib require("zlib"); const fs require(fs)// 压缩 1. createGzip .gz 2. createDeflate .deflate // const readStream fs.createReadStream(index.txt) // const writeStream fs.createWriteStream(index.txt.gz) // rea…

更换 Jenkins 插件下载源(解决 Jenkins 插件安装失败)【图文详细教程】

Jenkins 插件安装失败的情况 这里提一下&#xff0c;Jenkins 插件安装失败&#xff0c;不一定是下载源的问题&#xff0c;还有可能你下载的 Jenkins 的版本与插件的版本不匹配&#xff0c;Jenkins 的版本较低&#xff0c;而安装的插件是为新的 Jenkins 版本准备的&#xff0c;此…

web CSS笔记1

CSS(Cascading Style Sheets) 美化样式 CSS通常称为CSS样式表或层叠样式表&#xff08;级联样式表&#xff09;&#xff0c;主要用于设置HTML页面中的文本内容&#xff08;字体、大小、对齐方式等&#xff09;、图片的外形&#xff08;宽高、边框样式、边距等&#xff09;以及…

前端学习之用css和html做一个仿淘宝的导航栏

代码 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>仿淘宝界面案例</title><style>/* 最外层盒子 */.container{width: 270px;height: 385px;border: 1px solid rgb(255, 208, 0);bord…

探秘 RabbitMQ 的设计理念与核心技术要点

目录 一、消息中间件介绍 1.1 消息中间件的作用 二、RabbitMQ 2.1 核心概念 2.2 生产者发送消息过程 2.3 消费者接收消息过程 2.4 RabbitMQ 为何要引入信道(channel) 2.5 消费模式 一、消息中间件介绍 消息队列中间件&#xff08;message queue middleWare, MQ&#xff09;指…

Matlab|【免费】基于数据驱动的模型预测控制电力系统机组组合优化

目录 1 主要内容 2 部分代码 3 程序结果 4 下载链接 1 主要内容 该程序复现文章《Feature-Driven Economic Improvement for Network-Constrained Unit Commitment: A Closed-Loop Predict-and-Optimize Framework》&#xff0c;程序主要做的是一个基于数据驱动的电力系统机…

client-go中ListAndWatch机制,informer源码详解

文章首发地址&#xff1a; 学一下 (suxueit.com)https://suxueit.com/article_detail/s9UMb44BWZdDRfKqFv22 先上一张&#xff0c;不知道是那个大佬画的图 简单描述一下流程 client-go封装部分 以pod为例 、先List所有的Pod资源&#xff0c;然后通过已经获取的pod资源的最大版…

python—接口编写部分

最近准备整理一下之前学过的前端小程序知识笔记&#xff0c;形成合集。顺便准备学一学接口部分&#xff0c;希望自己能成为一个全栈嘿嘿。建议关注收藏&#xff0c;持续更新技术文档。 目录 前端知识技能树http请求浏览器缓存 后端知识技能树python_api&#xff1a;flaskflask…

保研复习概率论2

1.什么是随机变量的数学期望&#xff08;expected value&#xff09;&#xff1f; 如果X是离散型随机变量&#xff0c;其分布列为piP{Xxi}(i1,2...)&#xff0c;若级数绝对收敛&#xff0c;则称随机变量X的数学期望存在&#xff0c;并将的和称为随机变量X的数学期望&#xff0…

大型网站集群管理负载均衡

课程介绍 结合企业大规模应用&#xff0c;解决应用高并发问题&#xff0c;解决单节点故障问题&#xff0c;缓存数据库的应用。学完掌握知识点&#xff1a;企业应用实现四七层负载均衡&#xff0c;以及Nginx等应用的高可用性&#xff0c;Redis缓存数据库的部署应用以及高可用方…