首页 > 其他分享 >生成二维码

生成二维码

时间:2024-01-10 16:15:27浏览次数:25  
标签:image BufferedImage 生成 note 二维码 outImage outg new

生成二维码

工具类来源网络

<!-- 二维码 -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.1.0</version>
</dependency>

<!-- 使用了Base64 -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>

生成二维码工具类

package com.dem.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lichangben
 * @date 2021/8/5
 */
public class QRCodeUtils {

    
     // 默认是黑色
    private static final int QRCOLOR = 0xFF000000; 
    // 背景颜色
    private static final int BGWHITE = 0xFFFFFFFF; 
    // 二维码宽
    private static final int WIDTH = 400; 
    // 二维码高
    private static final int HEIGHT = 400; 


    // 用于设置QR二维码参数
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;
        {
            // 设置QR二维码的纠错级别(H为最高级别)具体级别信息
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            // 设置编码方式
            put(EncodeHintType.CHARACTER_SET, "utf-8");
            put(EncodeHintType.MARGIN, 0);
        }
    };

    /**
     * 生成带logo的二维码图片
     * note 二维码下方的标题,如果不需要为空即可
     * 返回字符串,将此字符串放入IMG标签的SRC即可
     */
    public static  String drawLogoQRCode(String qrUrl, String logoUrl,String note) {
        //logUrl 存放的绝对路径,如果存放在本项目的resource底下,可以用 某个类.class.getResource("/xxx.png").getPath()来获取
        File logoFile = new File(logoUrl);
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
            BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);

            // 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }

            int width = image.getWidth();
            int height = image.getHeight();
            if ( logoFile.exists()) {
                // 构建绘图对象
                Graphics2D g = image.createGraphics();
                // 读取Logo图片
                BufferedImage logo = ImageIO.read(logoFile);
                // 开始绘制logo图片
                g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
                g.dispose();
                logo.flush();
            }

            // 自定义文本描述
            if (StringUtils.isNotEmpty(note)) {
                // 新的图片,把带logo的二维码下面加上文字
                BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg = outImage.createGraphics();
                // 画二维码到新的面板
                outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
                // 画文字到新的面板
                outg.setColor(Color.BLACK);
                outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号
                int strWidth = outg.getFontMetrics().stringWidth(note);
                if (strWidth > 399) {
                    // //长度过长就截取前面部分
                    // 长度过长就换行
                    String note1 = note.substring(0, note.length() / 2);
                    String note2 = note.substring(note.length() / 2, note.length());
                    int strWidth1 = outg.getFontMetrics().stringWidth(note1);
                    int strWidth2 = outg.getFontMetrics().stringWidth(note2);
                    outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
                    BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
                    Graphics2D outg2 = outImage2.createGraphics();
                    outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                    outg2.setColor(Color.BLACK);
                    outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
                    outg2.drawString(note2, 200 - strWidth2 / 2,outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                    outg2.dispose();
                    outImage2.flush();
                    outImage = outImage2;
                } else {
                    outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
                }
                outg.dispose();
                outImage.flush();
                image = outImage;
            }

            image.flush();
            //写入输出流,用于转换
            ByteArrayOutputStream tmp = new ByteArrayOutputStream();
            ImageIO.write(image, "png", tmp);
            tmp.close();
            return "data:image/png;base64,"+(new String(Base64.encodeBase64(tmp.toByteArray())));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成不带logo的二维码图片
     * note 二维码下方的标题,如果不需要为空即可
     * 返回字符串,将此字符串放入IMG标签的SRC即可
     */
    public static  String drawLogoQRCodeNotLogo(String qrUrl, String note) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
            BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            // 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }
            int height = image.getHeight();
            // 自定义文本描述
            if (StringUtils.isNotEmpty(note)) {
                // 新的图片,把带logo的二维码下面加上文字
                BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg = outImage.createGraphics();
                // 画二维码到新的面板
                outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
                // 画文字到新的面板
                outg.setColor(Color.BLACK);
                outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号
                int strWidth = outg.getFontMetrics().stringWidth(note);
                if (strWidth > 399) {
                    // //长度过长就截取前面部分
                    // 长度过长就换行
                    String note1 = note.substring(0, note.length() / 2);
                    String note2 = note.substring(note.length() / 2, note.length());
                    int strWidth1 = outg.getFontMetrics().stringWidth(note1);
                    int strWidth2 = outg.getFontMetrics().stringWidth(note2);
                    outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
                    BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
                    Graphics2D outg2 = outImage2.createGraphics();
                    outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                    outg2.setColor(Color.BLACK);
                    outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
                    outg2.drawString(note2, 200 - strWidth2 / 2,outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                    outg2.dispose();
                    outImage2.flush();
                    outImage = outImage2;
                } else {
                    outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
                }
                outg.dispose();
                outImage.flush();
                image = outImage;
            }
            image.flush();
            //写入缓存区,用于转换
            ByteArrayOutputStream tmp = new ByteArrayOutputStream();
            ImageIO.write(image, "png", tmp);
            tmp.close();
            return "data:image/png;base64,"+(new String(Base64.encodeBase64(tmp.toByteArray())));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}

::: tip 提示
前端生成二维码 使用qrcode.js


qrcode.js 下载
:::

标签:image,BufferedImage,生成,note,二维码,outImage,outg,new
From: https://www.cnblogs.com/lichangben/p/17956690

相关文章

  • EF First 生成数据模型
    //创建目录:mkdirEFCoreScaffoldexample//进入目录:cdEFCoreScaffoldExample//创建控制台项目:dotnetnewconsole//添加依赖:dotnetaddpackageMicrosoft.EntityFrameworkCore.SqlServer--version7.0.15//添加依赖:dotnetaddpackageMicrosoft.EntityFrameworkCore.Design--v......
  • 软件测试/人工智能/全日制测试开发|利用ChatGPT自动生成自动化测试脚本
    自动化测试是软件测试过程中不可或缺的一部分,它能够提高测试效率,减少测试成本,保障软件质量。然而,编写和维护自动化测试脚本仍然是一个具有挑战性的任务,需要花费大量的时间和精力。学会借助ChatGPT自动生成自动化测试脚本,就可以减少编写自动化脚本的工作量,提高测试效率。如何借助Cha......
  • 随机生成每个日期的时分秒,同天的累计,略过12-14点
    <?php//洛杉矶时区date_default_timezone_set('America/Los_Angeles');$date_arr=['2023-11-10','2023-11-10','2023-11-10','2023-11-11','2023-11-11','2023-11-12�......
  • python系列教程218——生成器表达式
    声明:在人工智能技术教学期间,不少学生向我提一些python相关的问题,所以为了让同学们掌握更多扩展知识更好地理解AI技术,我让助理负责分享这套python系列教程,希望能帮到大家!由于这套python教程不是由我所写,所以不如我的AI技术教学风趣幽默,学起来比较枯燥;但它的知识点还是讲到位的了,也值......
  • 大麦订单生成器 大麦订单图一键生成 大麦演唱会门票订单生成
    1.可以一键添加,生成的假订单没有水印,界面也很真实。2.在软件中输入生成的信息,这是产品信息,选择生成的产品图像,最后生成它。教程:解压源码,导入数据库,修改数据库config/Congig 1、一键生成大麦演唱会订单截图,大麦电子票订单截图,效果逼真,高清无水印,2、使用简单,支持自定义订单内容;下......
  • 通过印模生成电子印章-Java源代码
    以下代码是处理印模图片的核心代码,通过以下代码可以将公章图片转换为电子印章图片。制作方式分为四步:1、在白纸上加盖印章;2、把加盖印章的白纸扫描,形成图片;3、将图片通过下面的代码进行自动透明化抠图处理;4、程序返回自动透明化抠图处理后的电子印章图片。5、处理后的电子印章效果(......
  • java生成企业公章图片源代码
    企业公章图片在电子签章业务中应用广泛,在电子签章应用过程中首先需要生成公章图片,然后再使用公章图片结合数字签名技术完成电子签,这样就实现了从可视化到不可篡改的数字化电子签章功能,以下是企业公章图片生成源代码。importcom.resrun.utils.Base64;importorg.apache.pdfbox.io.......
  • QRCoder1.4.3生成二维码,不依赖System.Drawing,解决"未能找到类型或命名空间名QRCode","
    生成二维码1(简单)包引用:<PackageReferenceInclude="QRCoder"Version="1.4.3"/>usingQRCoder;///<summary>///生成二维码///</summary>///<paramname="data">escape后的数据,防止中文等特殊字符引起问题</param>///<par......
  • 大麦演唱会电子票生成器,大麦电子票生成器
    1.可以一键添加,生成的假订单没有水印,界面也很真实。2.在软件中输入生成的信息,这是产品信息,选择生成的产品图像,最后生成它。教程:解压源码,导入数据库,修改数据库config/Congig 1、一键生成大麦演唱会订单截图,大麦电子票订单截图,效果逼真,高清无水印,2、使用简单,支持自定义订单内容;下......
  • Hardhat框架使用及生成交易trace
    Hardhat介绍hardhat-tutorial安装Hardhat框架安装nvmbrewinstallnvm~/.zshrc添加nvm配置#NVMCONFIGexportNVM_DIR="$HOME/.nvm" [-s"/usr/local/opt/nvm/nvm.sh"]&&\."/usr/local/opt/nvm/nvm.sh"#Thisloadsnvm [-s"/us......