利用Spring Boot+zxing,生成二维码还能这么简单

原文地址:https://mp.weixin.qq.com/s/e59SJFP87OX8pOIrFGMAEw

作者:Java碎碎念

在网站开发中,经常会遇到要生成二维码的情况,比如要使用微信支付、网页登录等,本文分享一个Spring Boot生成二维码的例子,这里用到了google的zxing工具类。

二维码简介:

  二维码又称为QR Code,QR全称是Quick Response,是一个近几年来移动设备上超流行的一种编码方式。二维码是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的。

主要应用场景如下:

  信息获取(名片、地图、WIFI密码、资料)

  网站跳转(跳转到微博、手机网站、网站)

  广告推送(用户扫码,直接浏览商家推送的视频、音频广告)

  手机电商(用户扫码、手机直接购物下单)

  防伪溯源(用户扫码、即可查看生产地;同时后台可以获取最终消费地)

  优惠促销(用户扫码,下载电子优惠券,抽奖)

  会员管理(用户手机上获取电子会员信息、VIP服务)

  手机支付(扫描商品二维码,通过银行或第三方支付提供的手机端通道完成支付)

  账号登录(扫描二维码进行各个网站或软件的登录)

二维码生成

1. 引入jar包

  pom.xml中引入zxing的jar包。

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

2. 编写工具类

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 javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;

public class QrCodeUtil {

    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    /**
     * 二维码尺寸
     */
    private static final int QRCODE_SIZE = 300;
    /**
     * LOGO宽度
     */
    private static final int WIDTH = 60;
    /**
     * LOGO高度
     */
    private static final int HEIGHT = 60;

    /**
     * 生成二维码图片流
     * @param content  二维码内容
     * @param imgPath  LOGO图片地址
     * @param needCompress 是否需要压缩
     * @return BufferedImage
     */
    private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入图片
        QrCodeUtil.insertImage(image, imgPath, needCompress);
        return image;
    }

    /**
     * 插入LOGO图片
     * @param source     二维码文件缓冲流
     * @param imgPath    LOGO图片地址
     * @param needCompress 是否需要压缩
     */
    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        // 压缩LOGO
        if (needCompress) {
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            // 绘制缩小后的图
            g.drawImage(image, 0, 0, null);
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成二维码
     * @param content  二维码内容
     * @param imgPath  LOGO文件地址
     * @param destPath 二维码存放地址
     * @param needCompress 是否需要压缩
     */
    public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QrCodeUtil.createImage(content, imgPath, needCompress);
        mkdirs(destPath);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    /**
     * 生成二维码
     * @param content 二维码内容
     * @param imgPath LOGO文件地址
     * @param needCompress 是否需要压缩
     * @return 二维码缓冲流
     */
    public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {
        return QrCodeUtil.createImage(content, imgPath, needCompress);
    }

    /**
     * 生成二维码
     * @param content  二维码内容
     * @param imgPath  LOGO图片地址
     * @param output   输出流
     * @param needCompress 是否需要压缩
     */
    public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
            throws Exception {
        BufferedImage image = QrCodeUtil.createImage(content, imgPath, needCompress);
        ImageIO.write(image, FORMAT_NAME, output);
    }

    /**
     * 生成二维码(没有LOGO,不压缩)
     * @param content  二维码内容
     * @param output   输出流
     */
    public static void encode(String content, OutputStream output) throws Exception {
        BufferedImage image = QrCodeUtil.createImage(content, null, false);
        ImageIO.write(image, FORMAT_NAME, output);
    }

    /**
     * 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
     * @param destPath 文件目录
     */
    private static void mkdirs(String destPath) {
        File file = new File(destPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

}

4. 编写测试方法

public static void main(String[] args) {
    try {
        String url = "weixin://wxpay/bizpayurl/up?pr=NwY5Mz9&groupid=00";
        String path = "D:\img\ww.jpg";
        QrCodeUtil.encode(url, null, path, false);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

5. 编写控制层代码

/**
  * 根据 url 生成 普通二维码
  */
@RequestMapping(value = "/createCommonQRCode")
public void createCommonQRCode(HttpServletResponse response, String url) throws Exception {
    ServletOutputStream stream = null;
    try {
        stream = response.getOutputStream();
        //使用工具类生成二维码
        QRCodeUtil.encode(url, stream);
    } catch (Exception e) {
        e.getStackTrace();
    } finally {
        if (stream != null) {
            stream.flush();
            stream.close();
        }
    }
}

/**
  * 根据 url 生成 带有logo二维码
  */
@RequestMapping(value = "/createLogoQRCode")
public void createLogoQRCode(HttpServletResponse response, String url) throws Exception {
    ServletOutputStream stream = null;
    try {
        stream = response.getOutputStream();
        String logoPath = Thread.currentThread().getContextClassLoader().getResource("").getPath() 
               + "templates" + File.separator + "logo.jpg";
        //使用工具类生成二维码
        QRCodeUtil.encode(url, logoPath, stream, true);
    } catch (Exception e) {
        e.getStackTrace();
    } finally {
        if (stream != null) {
            stream.flush();
            stream.close();
        }
    }
}
原文地址:https://www.cnblogs.com/huanshilang/p/11718342.html