Java基于Google zxing生成带logo的二维码图片

 更新时间:2023年10月15日 11:16:44   作者:smileNicky  
zxing是一个开放源码的,用java实现的多种格式的1D/2D条码图像处理库,本文主要介绍了Java基于Google zxing生成带logo的二维码图片,具有一定的参考价值,感兴趣的可以了解一下

环境准备

  • 开发环境

    • JDK 1.8
    • SpringBoot2.2.1
    • Maven 3.2+
  • 开发工具

    • IntelliJ IDEA
    • smartGit
    • Navicat15

添加maven配置

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.4.0</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.4.0</version>
</dependency>

创建比特矩阵

先创建比特矩阵,设置默认的宽度、高度、后缀名等等

 private static final String DEFAULT_CHAR_SET = "UTF-8";

private static final String DEFAULT_FORMAT_NAME = "JPG";


// 二维码宽度
private static final int DEFAULT_QR_CODE_WIDTH = 300;
// 二维码高度
private static final int DEFAULT_QR_CODE_HEIGHT = 300;

/**
 * 创建BitMatrix比特矩阵
 * @Date 2023/09/24 22:29
 * @Param contents 二维码里的内容
 * @Param width 二维码宽度
 * @param height 二维码高度
 * @return com.google.zxing.common.BitMatrix
 */
public static  BitMatrix createBitMatrix(String contents , int width , int height) throws WriterException, IOException {
    if (ObjectUtil.isNull(width)) {
        width = DEFAULT_QR_CODE_WIDTH;
    }
    if (ObjectUtil.isNull(height)) {
        height = DEFAULT_QR_CODE_HEIGHT;
    }

    Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 纠错等级L,M,Q,H
    hints.put(EncodeHintType.CHARACTER_SET, DEFAULT_CHAR_SET);// 编码utf-8
    hints.put(EncodeHintType.MARGIN, 1);  // 边距

    // 创建比特矩阵
    BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
            BarcodeFormat.QR_CODE, width, height, hints);
    return bitMatrix;

}

转换为BufferedImage

创建好比特矩阵后,转换为BufferedImage

 /**
 * 转换为BufferedImage
 * @Date 2023/09/24 22:32
 * @Param [bitMatrix]
 * @return java.awt.image.BufferedImage
 */
public static BufferedImage toBufferedImage(BitMatrix bitMatrix) throws IOException, WriterException {
    MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
    BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix, matrixToImageConfig);
    return bufferedImage;
}

加上二维码logo

给创建的二维码BufferedImage加上logo

 /**
 * 给二维码添加logo
  * @Date 2023/09/24 22:33
  * @Param [bufferedImage, logoFile]
  * @return java.awt.image.BufferedImage
  */
 public static BufferedImage addQrCodeLogo(BufferedImage bufferedImage, File logoFile) throws IOException {
     Graphics2D graphics = bufferedImage.createGraphics();
     int matrixWidth = bufferedImage.getWidth();
     int matrixHeigh = bufferedImage.getHeight();

     // 读取logo图片文件
     BufferedImage logo = ImageIO.read(logoFile);
     int logoWidth = logo.getWidth();
     int logoHeight = logo.getHeight();

     //  计算logo放置位置
     int x = bufferedImage.getWidth()  / 5*2;
     int y = bufferedImage.getHeight() / 5*2;
     int width = matrixWidth / 5;
     int height = matrixHeigh / 5;

     // 开始绘制图片
     graphics.drawImage(logo, x, y, width, height, null);
     graphics.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);
     graphics.setStroke(new BasicStroke(5.0F, 1, 1));
     graphics.setColor(Color.white);
     graphics.drawRect(x, y, logoWidth, logoHeight);

     graphics.dispose();
     bufferedImage.flush();
     return bufferedImage;
 }

测试

public static void main(String[] args) throws Exception {
     BufferedImage bufferedImage = toBufferedImage(createBitMatrix("https://blog.csdn.net", 300, 300));
     ImageIO.write(bufferedImage, "png", new File("D:/qrcode.jpg"));

     System.out.println(decodeQrCode(bufferedImage));

     BufferedImage logoQrCode = addQrCodeLogo(bufferedImage, new File("D://logo.png"));
     ImageIO.write(logoQrCode, "png", new File("D:/logoQrcode.jpg"));
 }

创建不带logo的二维码图片

在这里插入图片描述

创建带logo的二维码图片

在这里插入图片描述

附录

package com.example.common.util.qrcode;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

public class QrCodeGenerator {


    private static final String DEFAULT_CHAR_SET = "UTF-8";

    private static final String DEFAULT_FORMAT_NAME = "JPG";


    // 二维码宽度
    private static final int DEFAULT_QR_CODE_WIDTH = 300;
    // 二维码高度
    private static final int DEFAULT_QR_CODE_HEIGHT = 300;

    /**
     * 创建BitMatrix比特矩阵
     * @Date 2023/09/24 22:29
     * @Param contents 二维码里的内容
     * @Param width 二维码宽度
     * @param height 二维码高度
     * @return com.google.zxing.common.BitMatrix
     */
    public static  BitMatrix createBitMatrix(String contents , int width , int height) throws WriterException, IOException {
        if (ObjectUtil.isNull(width)) {
            width = DEFAULT_QR_CODE_WIDTH;
        }
        if (ObjectUtil.isNull(height)) {
            height = DEFAULT_QR_CODE_HEIGHT;
        }

        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 纠错等级L,M,Q,H
        hints.put(EncodeHintType.CHARACTER_SET, DEFAULT_CHAR_SET);// 编码utf-8
        hints.put(EncodeHintType.MARGIN, 1);  // 边距

        // 创建比特矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
                BarcodeFormat.QR_CODE, width, height, hints);
        return bitMatrix;

    }

    /**
     * 创建二维码,返回字节数组
     * @Date 2023/09/24 22:30
     * @Param contents 二维码里的内容
     * @Param imageFormat 图片后缀名
     * @Param width 二维码宽度
     * @param height 二维码高度
     * @return byte[]
     */
    public static byte[] createQrCode(String contents , String imageFormat , int width , int height) throws WriterException, IOException {
        if (StrUtil.isBlank(imageFormat)){
            imageFormat = DEFAULT_FORMAT_NAME;
        }
        BitMatrix bitMatrix = createBitMatrix(contents , width, height);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, os);
        return os.toByteArray();
    }

    /**
     * 创建二维码,返回base64字符串
     * @Date 2023/09/24 22:30
     * @Param contents 二维码里的内容
     * @Param imageFormat 图片后缀名
     * @Param width 二维码宽度
     * @param height 二维码高度
     * @return byte[]
     */
    public static String createQrCodeBase64(String contents , String imageFormat , int width , int height) throws WriterException, IOException {
        byte[] bytes =createQrCode(contents , imageFormat , width, height);
        return Base64.encode(bytes);
    }

    /**
     * 解码二维码
     * @Date 2023/09/24 22:32
     * @Param [image]
     * @return java.lang.String
     */
    public static String decodeQrCode(BufferedImage image) throws Exception {
        if (image == null) return StrUtil.EMPTY;
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, DEFAULT_CHAR_SET);
        Result result = new MultiFormatReader().decode(bitmap, hints);
        return result.getText();
    }

    /**
     * 转换为BufferedImage
     * @Date 2023/09/24 22:32
     * @Param [bitMatrix]
     * @return java.awt.image.BufferedImage
     */
    public static BufferedImage toBufferedImage(BitMatrix bitMatrix) throws IOException, WriterException {
        MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix, matrixToImageConfig);
        return bufferedImage;
    }

    /**
     * 给二维码添加logo
     * @Date 2023/09/24 22:33
     * @Param [bufferedImage, logoFile]
     * @return java.awt.image.BufferedImage
     */
    public static BufferedImage addQrCodeLogo(BufferedImage bufferedImage, File logoFile) throws IOException {
        Graphics2D graphics = bufferedImage.createGraphics();
        int matrixWidth = bufferedImage.getWidth();
        int matrixHeigh = bufferedImage.getHeight();

        // 读取logo图片文件
        BufferedImage logo = ImageIO.read(logoFile);
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        //  计算logo放置位置
        int x = bufferedImage.getWidth()  / 5*2;
        int y = bufferedImage.getHeight() / 5*2;
        int width = matrixWidth / 5;
        int height = matrixHeigh / 5;

        // 开始绘制图片
        graphics.drawImage(logo, x, y, width, height, null);
        graphics.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);
        graphics.setStroke(new BasicStroke(5.0F, 1, 1));
        graphics.setColor(Color.white);
        graphics.drawRect(x, y, logoWidth, logoHeight);

        graphics.dispose();
        bufferedImage.flush();
        return bufferedImage;
    }

    public static void main(String[] args) throws Exception {
        BufferedImage bufferedImage = toBufferedImage(createBitMatrix("https://blog.csdn.net", 300, 300));
        ImageIO.write(bufferedImage, "png", new File("D:/qrcode.jpg"));

        System.out.println(decodeQrCode(bufferedImage));

        BufferedImage logoQrCode = addQrCodeLogo(bufferedImage, new File("D://logo.png"));
        ImageIO.write(logoQrCode, "png", new File("D:/logoQrcode.jpg"));
    }

}

到此这篇关于Java基于Google zxing生成带logo的二维码图片的文章就介绍到这了,更多相关Java zxing生成带logo二维码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

相关文章

  • 在IDEA中创建Web项目的详细过程

    在IDEA中创建Web项目的详细过程

    这篇文章主要给大家介绍了关于在IDEA中创建Web项目的详细过程,很多朋友可能在学习java基础的时候已经熟练掌握了IDEA创建java项目的基本步骤,但随着学习技术的不断深入,不同的IDEA版本可能在项目的创建页面上出现些许的出入,需要的朋友可以参考下
    2023-10-10
  • Java带复选框的树(Java CheckBox Tree)实现和应用

    Java带复选框的树(Java CheckBox Tree)实现和应用

    这篇文章主要为大家详细介绍了Java带复选框的树实现和应用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11
  • mybatis拦截器无法注入spring bean的问题解决

    mybatis拦截器无法注入spring bean的问题解决

    本文主要介绍了mybatis拦截器无法注入spring bean的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-02-02
  • spring boot启动时mybatis报循环依赖的错误(推荐)

    spring boot启动时mybatis报循环依赖的错误(推荐)

    今天小编抽时间给大家分享spring boot启动时mybatis报循环依赖的错误,非常不错,具有参考借鉴价值,需要的朋友参考下吧
    2017-12-12
  • 使用SpringBoot与EasyExcel实现复杂的导入导出

    使用SpringBoot与EasyExcel实现复杂的导入导出

    这篇文章主要介绍了使用SpringBoot与EasyExcel实现复杂的导入导出,EasyExcel是一个快速解决大文件内存溢出的Excel处理工具,它能让你在不用考虑性能、内存等因素的情况下,快速完成Excel的读、写等功能,需要的朋友可以参考下
    2023-10-10
  • SpringBoot如何上传图片

    SpringBoot如何上传图片

    这篇文章主要介绍了SpringBoot如何上传图片,帮助大家更好的理解和学习springboot框架,感兴趣的朋友可以了解下
    2020-09-09
  • 引入QQ邮箱发送验证码进行安全校验功能实现

    引入QQ邮箱发送验证码进行安全校验功能实现

    最近遇到这样的需求用户输入自己的邮箱,点击获取验证码,后台会发送一封邮件到对应邮箱中,怎么实现呢?下面小编给大家带来了引入QQ邮箱发送验证码进行安全校验功能,需要的朋友可以参考下
    2023-02-02
  • 解决版本不兼容Jar包冲突问题

    解决版本不兼容Jar包冲突问题

    在和三方对接的过程中,我们可能会不断引入一些三方jar包,但这个时候就有可能出现一个项目需要依赖两个版本不同且功能不兼容的jar包,本文主要介绍了解决版本不兼容Jar包冲突问题,感兴趣的可以了解一下
    2023-10-10
  • Eclipse中导出码云上的项目方法(图文教程)

    Eclipse中导出码云上的项目方法(图文教程)

    下面小编就为大家带来一篇Eclipse中导出码云上的项目方法(图文教程)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • 详解在SpringBoot应用中获取应用上下文方法

    详解在SpringBoot应用中获取应用上下文方法

    本篇文章主要介绍了详解在SpringBoot应用中获取应用上下文方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
    2017-04-04

最新评论