Java生成二维码的实例代码

 更新时间:2020年09月09日 10:04:59   作者:崔笑颜  
这篇文章主要介绍了Java生成二维码的实例代码,帮助大家更好的理解和使用Java,感兴趣的朋友可以了解下

使用开源的一维/二维码图形处理库zxing GitHub地址

引入依赖

<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>core</artifactId>
  <version>3.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>javase</artifactId>
  <version>3.3.0</version>
</dependency>

封装工具类

package com.app.utils;
 
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 
/**
 * @title 生成二维码工具类
 * @author zch
 * @discribtion
 * @Date 2020年1月3日 下午4:26:05
 * @vision V1.0
 */
public class QRCodeUtil
{
  private static final int width = 200; // 图像宽度
  
  private static final int height = 200; // 图像高度
  
  private static final int ON_COLOR = 0xFF000001;
  
  private static final int OFF_COLOR = 0xFFFFFFFF;
  
  /**
   * @title 生成二维码图片
   * @discribtion
   * @author zch
   * @Date 2020年1月3日 下午3:27:21
   * @param width 二维码宽度,默认为200
   * @param height 二维码高度,默认为200
   * @param content 二维码内容,必填
   * @param logoPath logo图片路径,若为空则生成不带logo的二维码
   * @param imgPath 生成二维码文件夹路径
   * @param imgName 生成二维码图片名称,必填
   * @param suffix 生成二维码图片后缀类型,例如:gif,必填
   * @vision V1.0
   */
  public static boolean generateQRImage(Integer width, Integer height, String content, String logoPath, String imgPath, String imgName, String suffix)
  {
    if (content == null || imgName == null || suffix == null)
    {
      return false;
    }
    try
    {
      width = width == null ? QRCodeUtil.width : width;
      height = height == null ? QRCodeUtil.height : height;
      if (logoPath != null && !"".equals(logoPath.trim()))
      {
        QREncode(width, height, content, logoPath, imgPath, imgName, suffix);
      }
      else
      {
        QREncode(width, height, content, imgPath, imgName, suffix);
      }
      return true;
    }
    catch (Exception e)
    {
      e.printStackTrace();
      return false;
    }
  }
  
  /**
   * @title 生成二维码
   * @discribtion
   * @author zch
   * @Date 2020年1月3日 下午3:27:21
   * @vision V1.0
   */
  private static void QREncode(int width, int height, String content, String imgPath, String imgName, String suffix)
    throws Exception
  {
    File filePath = new File(imgPath);
    if (!filePath.exists())
    {
      filePath.mkdirs();
    }
    File imageFile = new File(imgPath, imgName);
    Map<EncodeHintType, Object> hints = new HashMap<>();
    // 内容编码格式
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    // 指定纠错等级
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    // 设置二维码边的空度,非负数
    hints.put(EncodeHintType.MARGIN, 1);
    BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
    MatrixToImageWriter.writeToPath(bitMatrix, suffix, imageFile.toPath());// 输出原图片
  }
  
  /**
   * @title 生成带logo的二维码
   * @discribtion
   * @author zch
   * @Date 2020年1月3日 下午3:27:21
   * @vision V1.0
   */
  private static void QREncode(int width, int height, String content, String logoPath, String imgPath, String imgName, String suffix)
    throws Exception
  {
    File filePath = new File(imgPath);
    if (!filePath.exists())
    {
      filePath.mkdirs();
    }
    File imageFile = new File(imgPath, imgName);
    Map<EncodeHintType, Object> hints = new HashMap<>();
    // 内容编码格式
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    // 指定纠错等级
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    // 设置二维码边的空度,非负数
    hints.put(EncodeHintType.MARGIN, 1);
    BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
    MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(ON_COLOR, OFF_COLOR);
    BufferedImage bufferedImage = LogoMatrix(MatrixToImageWriter.toBufferedImage(bitMatrix, matrixToImageConfig), new File(logoPath));
    ImageIO.write(bufferedImage, suffix, imageFile);// 输出带logo图片
  }
  
  /**
   * @title 二维码图片添加logo
   * @discribtion 
   * @author zch
   * @Date 2020年1月3日 下午3:27:21
   * @param matrixImage 源二维码图片
   * @param logoFile logo图片
   * @vision V1.0
   */
  private static BufferedImage LogoMatrix(BufferedImage matrixImage, File logoFile)
    throws IOException
  {
    // 读取二维码图片,并构建绘图对象
    Graphics2D gs = matrixImage.createGraphics();
    int matrixWidth = matrixImage.getWidth();
    int matrixHeigh = matrixImage.getHeight();
    int ratioWidth = matrixWidth * 2 / 10;
    int ratioHeight = matrixHeigh * 2 / 10;
    // 读取Logo图片
    BufferedImage logo = ImageIO.read(logoFile);
    int logoWidth = logo.getWidth(null) > ratioWidth ? ratioWidth : logo.getWidth(null);
    int logoHeight = logo.getHeight(null) > ratioHeight ? ratioHeight : logo.getHeight(null);
    int x = (matrixWidth - logoWidth) / 2;
    int y = (matrixHeigh - logoHeight) / 2;
    
    // 绘制
    gs.drawImage(logo, x, y, logoWidth, logoHeight, null);
    gs.setColor(Color.BLACK);
    gs.setBackground(Color.WHITE);
 
    gs.dispose();
    matrixImage.flush();
    return matrixImage;
  }
}

测试生成二维码

QRCodeUtil.generateQRImage(null, null, "https://blog.csdn.net/qq_34928194", null, "E:/", "test.gif", "gif");

以上就是Java生成二维码的实例代码的详细内容,更多关于Java生成二维码的资料请关注脚本之家其它相关文章!

相关文章

  • 显示IntelliJ IDEA工具的Run Dashboard功能图文详解

    显示IntelliJ IDEA工具的Run Dashboard功能图文详解

    这篇文章主要介绍了显示IntelliJ IDEA工具的Run Dashboard功能,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-07-07
  • 使用InputStream的available()能否用来判断当前流是否读取到文件

    使用InputStream的available()能否用来判断当前流是否读取到文件

    这篇文章主要介绍了使用InputStream的available()能否用来判断当前流是否读取到文件问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • Java中Elasticsearch的核心概念详解

    Java中Elasticsearch的核心概念详解

    这篇文章主要介绍了Java中Elasticsearch的核心概念详解,Elasticsearch 是一个分布式、免费和开放的搜索和分析引擎,适用于所有类型的数据,包括文本、数字、地理空间、结构化和非结构化数据,需要的朋友可以参考下
    2023-07-07
  • springdata jpa使用Example快速实现动态查询功能

    springdata jpa使用Example快速实现动态查询功能

    这篇文章主要介绍了springdata jpa使用Example快速实现动态查询功能,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • Netty分布式高性能工具类recycler的使用及创建

    Netty分布式高性能工具类recycler的使用及创建

    这篇文章主要为大家介绍了Netty分布式高性能工具类recycler的使用和创建,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2022-03-03
  • Spring Boot Reactor 整合 Resilience4j详析

    Spring Boot Reactor 整合 Resilience4j详析

    这篇文章主要介绍了Spring Boot Reactor整合Resilience4j详析,文章通过引入pom包展开详细介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下
    2022-09-09
  • Java使用泛型Class实现消除模板代码

    Java使用泛型Class实现消除模板代码

    Class作为实现反射功能的类,在开发中经常会用到,然而,当Class遇上泛型后,事情就变得不是那么简单了,所以本文就来讲讲Java如何使用泛型Class实现消除模板代码,需要的可以参考一下
    2023-06-06
  • 如何在pom文件中引入本地jar包并打包

    如何在pom文件中引入本地jar包并打包

    在项目中使用本地JAR文件的方法有很多,下面这篇文章主要给大家介绍了关于如何在pom文件中引入本地jar包并打包的相关资料,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2023-06-06
  • 浅谈Java中Spring Boot的优势

    浅谈Java中Spring Boot的优势

    在本篇文章中小编给大家分析了Java中Spring Boot的优势以及相关知识点内容,兴趣的朋友们可以学习参考下。
    2018-09-09
  • java中的内部类详细总结

    java中的内部类详细总结

    内部类不是很好理解,但说白了其实也就是一个类中还包含着另外一个类。如同一个人是由大脑、肢体、器官等身体结果组成,而内部类相当于其中的某个器官之一,例如心脏:它也有自己的属性和行为(血液、跳动)
    2013-10-10

最新评论