SpringBoot实战:项目中生成二维码的正确姿势

引言

二维码原理与唯一性保障
二维码将信息编码成黑白图形,通过扫描设备快速识别并解码。其复杂算法确保即使信息相似,二维码也独一无二。各平台采用管理系统分配二维码,避免重复。在物流等场景,为每个物品分配唯一追踪号生成二维码,确保不误扫。二维码的唯一性由复杂编码和严格管理共同保障,程序停运亦不影响其有效性。此技术覆盖生活各方面,极大提升便利性与安全性。

本文将介绍如何在一张背景图中嵌入生成的二维码和中文文字。

一、代码示例:简单生成二维码

项目的 pom.xml 文件中引用二维码相关依赖:

<!-- https://mvnrepository.com/artifact/com.google.zxing/zxing-parent -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>zxing-parent</artifactId>
            <version>3.5.0</version>
            <type>pom</type>
        </dependency>

创建生成二维码的工具类:

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.hvit.user.yst.request.CreateQrcodeRequest;
import org.apache.commons.lang3.StringUtils;
 
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

编写生成二维码的方法

// 生成二维码图片
    // text:二维码内容
    // size: 二维码尺寸
    private static BufferedImage generateQRCode(String text, int size) {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        try {
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix bitMatrix = writer.encode(text, BarcodeFormat.QR_CODE, size, size, hints);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            BufferedImage qrImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D graphics = qrImage.createGraphics();
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, size, size);
            graphics.setColor(Color.BLACK);
 
            for (int x = 0; x < size; x++) {
                for (int y = 0; y < size; y++) {
                    if (bitMatrix.get(x, y)) {
                        graphics.fillRect(x, y, 1, 1);
                    }
                }
            }
 
            // 渲染二维码
            Graphics2D graphics1 = qrImage.createGraphics();
            // 添加蓝色边框
            int borderSize = 10; // 边框大小
            Color myColor = new Color(0x19, 0x76, 0xFF); // 红色
            graphics1.setColor(myColor);
            graphics1.fillRect(0, 0, size, borderSize); // 上边框
            graphics1.fillRect(0, 0, borderSize, size); // 左边框
            graphics1.fillRect(size - borderSize, 0, borderSize, size); // 右边框
            graphics1.fillRect(0, size - borderSize, size, borderSize); // 下边框
 
            return qrImage;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

生成二维码如图:

SpringBoot实战:项目中生成二维码的正确姿势

二、代码示例:在背景图片上添加文字


在工具类中添加相应方法:

// 在图片上添加图片
    private static void addImageToImage(BufferedImage baseImage, BufferedImage overlayImage, int x, int y) {
        Graphics2D g2d = baseImage.createGraphics();
        g2d.drawImage(overlayImage, x, y, null);
        g2d.dispose();
    }
 
    // 在图片上添加文本,支持手动换行,文本水平居中
    private static void addTextToImage(BufferedImage baseImage, String text, Font font, Color color, int maxWidth, int y) {
        Graphics2D g2d = baseImage.createGraphics();
        g2d.setFont(font);
        g2d.setColor(color);
 
        FontMetrics fm = g2d.getFontMetrics();
        int lineHeight = fm.getHeight();
        int currentY = y;
        String[] lines = text.split("n");
 
        for (String line : lines) {
            int lineWidth = fm.stringWidth(line);
            int lineX = (maxWidth - lineWidth) / 2; // 居中
            g2d.drawString(line, lineX, currentY);
            currentY += lineHeight;
        }
 
        g2d.dispose();
    }

调用该方法:

public static void main(String[] args) throws Exception {
 
        // 1. 读取原始图片
        BufferedImage image = null;
        try {
            image = ImageIO.read(new File("C:\Users\caozhen\Desktop\图片素材\1.png")); // 替换成您的图片路径
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        if (image == null) {
            System.err.println("无法读取图片");
            return;
        }
        // 2. 在图片上添加透明的二维码
        String qrText = "https://qhdm.mzt.zj.gov.cn:9090/szmp/#/wait?code=b20267e5298948a2bca5de8d4a8081a4&type=dz&timeStrap=1694503662057"; // 替换成您的二维码文本
        int qrSize = 500; // 二维码尺寸
        BufferedImage qrCodeImage = generateQRCode(qrText, qrSize);
        int qrX = (image.getWidth() - qrSize) / 2;
        int qrY = 1050; // 设置二维码的垂直位置
        addImageToImage(image, qrCodeImage, qrX, qrY);
 
        // 3. 在图片上添加中文文本,支持手动换行
        String chineseText = "二维码背景上添加的文字";
        Font font = new Font("微软雅黑", Font.BOLD, 70); // 替换成所需的字体和大小
        Color textColor = Color.BLACK; // 文本颜色
        int textX = 20; // 文本左侧的边距
        int textY = 800; // 设置文本的垂直位置
        int textWidth = image.getWidth() - 40; // 文本可用的宽度
        addTextToImage(image, chineseText, font, textColor, textWidth, textY);
 
        // 4. 保存带有二维码和文本的图片
        try {
            ImageIO.write(image, "png", new File("C:\Users\caozhen\Desktop\图片素材\output.png")); // 替换成保存的文件路径
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

效果展示:

SpringBoot实战:项目中生成二维码的正确姿势




原文始发于微信公众号(Java技术前沿):SpringBoot实战:项目中生成二维码的正确姿势

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/299735.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!