Java生成二维码的实例代码

所属分类: 软件编程 / java 阅读数: 109
收藏 0 赞 0 分享

使用开源的一维/二维码图形处理库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生成二维码的资料请关注脚本之家其它相关文章!

更多精彩内容其他人还在看

Spring boot将配置属性注入到bean类中

本篇文章主要介绍了Spring boot将配置属性注入到bean类中,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Java正则判断日期格式是否正确的方法示例

这篇文章主要介绍了Java正则判断日期格式是否正确的方法,结合实例形式分析了Java针对日期字符串正则判断的相关操作技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

java Future 接口使用方法详解

这篇文章主要介绍了java Future 接口使用方法详解,Future接口是Java线程Future模式的实现,可以来进行异步计算的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

Java 读取外部资源的方法详解及实例代码

这篇文章主要介绍了Java 读取外部资源的方法详解及实例代码的相关资料,经常有读取外部资源的要求,如配置文件等等需要读取,需要的朋友可以参考下
收藏 0 赞 0 分享

Java正则表达式之split()方法实例详解

这篇文章主要介绍了Java正则表达式之split()方法,结合实例形式较为详细的分析了split方法的功能、使用方法及相关注意事项,需要的朋友可以参考下
收藏 0 赞 0 分享

Java 存储模型和共享对象详解

这篇文章主要介绍了Java 存储模型和共享对象详解的相关资料,对Java存储模型,可见性和安全发布的问题是起源于Java的存储结构及共享对象安全,需要的朋友可以参考下
收藏 0 赞 0 分享

Java使用正则表达式实现找出数字功能示例

这篇文章主要介绍了Java使用正则表达式实现找出数字功能,结合实例形式分析了Java针对数字的匹配查找及非数字替换操作相关实现技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Spring核心IoC和AOP的理解

本文主要介绍了Spring核心IoC和AOP的相关知识。具有很好的参考价值,下面跟着小编一起来看下吧
收藏 0 赞 0 分享

详解Spring AOP 拦截器的基本实现

本篇文章主要介绍了详解Spring AOP 拦截器的基本实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Mybatis 中的一对一,一对多,多对多的配置原则示例代码

这篇文章主要介绍了 Mybatis 中的一对一,一对多,多对多的配置原则示例代码,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多