springboot里 用zxing 生成二维码

news2024/9/24 23:26:00

引入pom

		<!--二维码依赖-->
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>3.3.3</version>
		</dependency>
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.3.3</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.28</version>
			<scope>provided</scope>
		</dependency>

核心方法

    private static final int QRCODE_SIZE = 320; // 二维码尺寸,宽度和高度均是320
    private static final String FORMAT_TYPE = "PNG"; // 二维码图片类型

    /**
     * 获取二维码图片
     *
     * @param dataStr    二维码内容
     * @param needLogo   是否需要添加logo
     * @param bottomText 底部文字       为空则不显示
     * @return
     */
    @SneakyThrows
    public static BufferedImage getQRCodeImage(String dataStr, boolean needLogo, String bottomText) {
        if (dataStr == null) {
            throw new RuntimeException("未包含任何信息");
        }
        HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");    //定义内容字符集的编码
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);        //定义纠错等级
        hints.put(EncodeHintType.MARGIN, 1);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(dataStr, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);

        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        int tempHeight = height;
        if (StringUtils.hasText(bottomText)) {
            tempHeight = tempHeight + 12;
        }
        BufferedImage image = new BufferedImage(width, tempHeight, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        // 判断是否添加logo
        if (needLogo) {
            insertLogoImage(image);
        }
        // 判断是否添加底部文字
        if (StringUtils.hasText(bottomText)) {
            addFontImage(image, bottomText);
        }
        return image;
    }

    /**
     * 插入logo图片
     *
     * @param source 二维码图片
     * @throws Exception
     */
    private static void insertLogoImage(BufferedImage source) throws Exception {
        // 默认logo放于resource/static/目录下
        ClassPathResource classPathResource = new ClassPathResource("static/xbk.jpg");
        InputStream inputStream = classPathResource.getInputStream();
        if (inputStream == null || inputStream.available() == 0) {
            return;
        }
        Image src = ImageIO.read(inputStream);
        int width = 30;
        int height = 30;

        Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null); // 绘制缩小后的图
        g.dispose();
        src = image;

        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    private static void addFontImage(BufferedImage source, String declareText) {
        //生成image
        int defineWidth = QRCODE_SIZE;
        int defineHeight = 20;
        BufferedImage textImage = new BufferedImage(defineWidth, defineHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) textImage.getGraphics();
        //开启文字抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,   RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, defineWidth, defineHeight);
        g2.setPaint(Color.BLACK);
        FontRenderContext context = g2.getFontRenderContext();
        //部署linux需要注意 linux无此字体会显示方块,传入null选择默认字体
        Font font = new Font(null, Font.BOLD, 15);
        g2.setFont(font);
        LineMetrics lineMetrics = font.getLineMetrics(declareText, context);
        FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);
        float offset = (defineWidth - fontMetrics.stringWidth(declareText)) / 2;
        float y = (defineHeight + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;
        g2.drawString(declareText, (int) offset, (int) y);

        Graphics2D graph = source.createGraphics();
        //开启文字抗锯齿
        graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,   RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        //添加image
        int width = textImage.getWidth(null);
        int height = textImage.getHeight(null);

        Image src = textImage;
        graph.drawImage(src, 0, QRCODE_SIZE - 8, width, height, Color.WHITE, null);
        graph.dispose();
    }

其中logo图片存放的路径为:resource/static/
在这里插入图片描述

调用

import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/qrcode")
public class QrCodeController {

    //1、生成带logo和底部文字得二维码
    @SneakyThrows
    @GetMapping("/getQrCode1")
    public void getQrCode1(HttpServletResponse response) {
        String content="test";
        String bottomTxt="01";
        ServletOutputStream os = response.getOutputStream();
        BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(content,true,bottomTxt);
        response.setContentType("image/png");
        ImageIO.write(bufferedImage,"png",os);
    }
    //2、生成不带logo和带底部文字的二维码
    @SneakyThrows
    @GetMapping("/getQrCode2")
    public void getQrCode2(HttpServletResponse response) {
        String content="test";
        ServletOutputStream os = response.getOutputStream();
        BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(content,false,null);
        response.setContentType("image/png");
        ImageIO.write(bufferedImage,"png",os);
    }
    //3、生成默认带logo不带底部文字得二维码
    @SneakyThrows
    @GetMapping("/getQrCode3")
    public void getQrCode3(HttpServletResponse response) {
        String content="test";
        ServletOutputStream os = response.getOutputStream();
        BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(content,true,null);
        response.setContentType("image/png");
        ImageIO.write(bufferedImage,"png",os);
    }
    //3、生成不带logo带底部文字得二维码
    @SneakyThrows
    @GetMapping("/getQrCode4")
    public void getQrCode4(HttpServletResponse response) {
        String content="test";
        String bottomTxt="01";
        ServletOutputStream os = response.getOutputStream();
        BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(content,false,bottomTxt);
        response.setContentType("image/png");
        ImageIO.write(bufferedImage,"png",os);
    }

    //5、生成不带logo带底部文字的二维码,返回base64
    @SneakyThrows
    @GetMapping("/getQrCode5")
    @ResponseBody
    public Object getQrCode5() {
        String content="test";
        String bottomTxt="01";
        BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage(content,false,bottomTxt);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
            ImageIO.write(bufferedImage, "png", baos);//写入流中
        byte[] bytes = baos.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        String generateQrCode="data:image/jpg;base64," + png_base64;
        Map<String,String> map = new HashMap<>();
        map.put("generateQrCode",generateQrCode);
        return map;
    }

}

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

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

相关文章

【分类讨论】CF1674 E

Problem - E - Codeforces 题意&#xff1a; 思路&#xff1a; 样例&#xff1a; 这种分类讨论的题&#xff0c;主要是去看答案的最终来源是哪几种情况&#xff0c;这几种情况得不重不漏 Code&#xff1a; #include <bits/stdc.h>#define int long longusing i64 lon…

尚硅谷css3笔记

目录 一、新增长度单位 二、新增盒子属性 1.border-box 怪异盒模型 2.resize 调整盒子大小 3.box-shadow 盒子阴影 案例&#xff1a;鼠标悬浮盒子上时&#xff0c;盒子有一个过度的阴影效果 三、新增背景属性 1.background-origin 设置背景图的原点 2.background-clip 设置背…

基于IMX6ULLmini的linux裸机开发系列一:汇编点亮LED

思来想去还是决定记录一下点灯&#xff0c;毕竟万物皆点灯嘛 编程步骤 使能GPIO时钟 设置引脚复用为GPIO 设置引脚属性(上下拉、速率、驱动能力) 控制GPIO引脚输出高低电平 使能GPIO时钟 其实和32差不多 先找到控制LED灯的引脚&#xff0c;也就是原理图 文件名 C:/Us…

自动提示功能消失解决方案

如果绿叶子是不可点击状态&#xff0c;可以点一下列表中的配置文件

43、TCP报文(一)

本节内容开始&#xff0c;我们正式学习TCP协议中具体的一些原理。首先&#xff0c;最重要的内容仍然是这个协议的封装结构和首部格式&#xff0c;因为这里面牵扯到一些环环相扣的知识点&#xff0c;例如ACK、SYN等等&#xff0c;如果这些内容不能很好的理解&#xff0c;那么后续…

A. Copil Copac Draws Trees(Codeforces Round 875 (Div. 1))

Copil Copac is given a list of n − 1 n-1 n−1 edges describing a tree of n n n vertices. He decides to draw it using the following algorithm: Step 0 0 0: Draws the first vertex (vertex 1 1 1). Go to step 1 1 1.Step 1 1 1: For every edge in the inpu…

号外号外,最经典的16S数据库Greengenes2更新啦!!!

没错&#xff0c;这是真的&#xff0c;沉积十年之后&#xff0c;多样性研究中最经典的16S数据库——Greengenes数据库&#xff0c;竟&#xff01;然&#xff01;更&#xff01;新&#xff01;了&#xff01;惊不惊喜&#xff01;意不意外&#xff01; 遥想当年小编还是一个小白…

vue 数字递增(滚动从0到)

使用 html <Incremental :startVal"0" :endVal"1000" :duration"500" />js&#xff1a; import Incremental from /utils/num/numViewjs let lastTime 0 const prefixes webkit moz ms o.split( ) // 各浏览器前缀let requestAnimatio…

基于YOLOv5n/s/m不同参数量级模型开发构建茶叶嫩芽检测识别模型,使用pruning剪枝技术来对模型进行轻量化处理,探索不同剪枝水平下模型性能影响

今天有点时间就想着之前遗留的一个问题正好拿过来做一下看看&#xff0c;主要的目的就是想要对训练好的目标检测模型进行剪枝处理&#xff0c;这里就以茶叶嫩芽检测数据场景为例了&#xff0c;在我前面的博文中已经有过相关的实践介绍了&#xff0c;感兴趣的话可以自行移步阅读…

QT的设计器介绍

设计器介绍 Qt制作 UI 界面&#xff0c;一般可以通过UI制作工具QtDesigner和纯代码编写两种方式来实现。纯代码实现暂时在这里不阐述了在后续布局章节详细说明&#xff0c;QtDesigner已经继承到开发环境中&#xff0c;在工程中直接双击ui文件就可以直接在QtDesigner设计器中打…

AtCoder Beginner Contest 314 E题题解

文章目录 Roulettes问题建模问题分析1.分析每个转盘对所求的作用2.从集合的角度思考每个积分的贡献代码 Roulettes 问题建模 给定n个轮盘&#xff0c;每个轮盘上有p个积分&#xff0c;每次转动轮盘需要一定的代价&#xff0c;在转动轮盘后可以等概率获得p个积分中的一个&#…

【通俗易懂】如何使用GitHub上传文件,如何用git在github上传文件

目录 创建 GitHub 仓库 使用 Git 进行操作 步骤 1&#xff1a;初始化本地仓库 步骤 2&#xff1a;切换默认分支 步骤 3&#xff1a;连接到远程仓库 步骤 4&#xff1a;获取远程更改 步骤 5&#xff1a;添加文件到暂存区 步骤 6&#xff1a;提交更改 步骤 7&#xff1a…

频繁full gc 调参

Error message from spark is:java.lang.Exception: application_1678793738534_17900289 Driver Disassociated [akka.tcp://sparkDriverClient11.71.243.117:37931] <- [akka.tcp://sparkYarnSQLAM9.10.130.149:38513] disassociated! 日志里频繁full gc &#xff0c;可以…

nginx代理请求到内网不同服务器

需求&#xff1a;之前用的是frp做的内网穿透&#xff0c;但是每次电脑断电重启&#xff0c;路由或者端口会冲突&#xff0c;现在使用汉土云盒替换frp。 需要把公网ip映射到任意一台内网服务器上&#xff0c;然后在这台内网服务器上用Nginx做代理即可访问内网其它服务器&#xf…

微服务中间件--微服务保护

微服务保护 微服务保护a.sentinelb.sentinel限流规则1) 流控模式1.a) 关联模式1.b) 链路模式 2) 流控效果2.a) 预热模式2.b) 排队等待 3) 热点参数限流 c.隔离和降级1) Feign整合Sentinel2) 线程隔离2.a) 线程隔离&#xff08;舱壁模式&#xff09; 3) 熔断降级3.a) 熔断策略-慢…

Xshell安装使用教程安排~

简介 Xshell 是一个强大的安全终端模拟软件&#xff0c;它支持SSH1, SSH2, 以及Microsoft Windows 平台的TELNET 协议。Xshell 通过互联网到远程主机的安全连接以及它创新性的设计和特色帮助用户在复杂的网络环境中享受他们的工作。 Xshell可以在Windows界面下用来访问远端不…

蔚来李斌卖手机:安卓系统,苹果售价,一年一发

‍作者 | Amy 编辑 | 德新 车圈大佬的玩法真让人寻不着套路&#xff01; 苹果的库克和小米的雷布斯&#xff0c;甚至是FF贾老板准备许久&#xff0c;都想分一块新能源车的蛋糕&#xff0c;蔚来李斌却反手进军手机界&#xff0c;从宣布造手机到手机入网仅仅隔了一年。 近期…

微盟集团中报增长稳健 重点发力智慧零售AI赛道

零售数字化进程已从渠道构建走向了用户的深度运营。粗放式用户运营体系无法适应“基于用户增长所需配套的精细化运营能力”,所以需要有个体、群体、个性化、自动化运营——即在对的时候、以对的方式、把对的内容推给用户。 出品|产业家 2023年已经过半&#xff0c;经济复苏成为…

生信豆芽菜-两组比较的柱状图

网址&#xff1a;http://www.sxdyc.com/visualsPlotMutiBar 1、数据准备 准备一个两列的数据 2、输入图片的宽度和高度&#xff0c;如果这里选择不转置&#xff0c;选择颜色&#xff0c;这里的颜色个数由输入数据第一列分组的个数决定&#xff0c;如果选择转置&#xff0c;选…

随手笔记——g2o实现BA

随手笔记——g2o实现BA 说明源代码 说明 源代码 bundle_adjustment_g2o.cpp #include <g2o/core/base_vertex.h> #include <g2o/core/base_binary_edge.h> #include <g2o/core/block_solver.h> #include <g2o/core/optimization_algorithm_levenberg.h&…