今日总结 – SpringBoot 2.2.5 整合ZXing

说明

  1. ZXing,一个支持在图像中解码和生成条形码(如二维码、PDF 417、EAN、UPC、Aztec、Data Matrix、Codabar)的库。ZXing(“zebra crossing”)是一个开源的、多格式的、用Java实现的一维/二维条码图像处理库,具有到其他语言的端口。
  2. GitHub地址,猛戳:https://github.com/zxing/zxing
  3. API文档,猛戳:https://zxing.github.io/zxing/apidocs/index.html
  4. 介绍文档,猛戳:https://zxing.github.io/zxing/

完整代码地址在结尾!!

第一步,在pom.xml加入依赖,如下

<!-- 二维码支持包 -->

<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>

第二步,编写application.yml配置文件,如下

server:

  port: 8187

spring:

  application:

    name: zxing-demo-server

# qr配置

qr:

  code:

    charset: utf-8

    width: 300

    height: 300

    logoWidth: 60

    logoHeight: 60

    picType: jpg

第三步,创建QrCodeConfig配置文件,如下

import lombok.Data;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

import java.io.Serializable;

/**

 * QrCodeConfig
 *
 * @author luoyu
 * @date 2018/10/19 18:47
 * @description 二维码配置类
 */
@Data
@Configuration
public class QrCodeConfig implements Serializable {

    private static final long serialVersionUID = 1L;

    @Value("${qr.code.charset}")

    private String configCharset;

    @Value("${qr.code.width}")

    private Integer configWidth;

    @Value("${qr.code.height}")

    private Integer configHeight;

    @Value("${qr.code.logoWidth}")

    private Integer configLogoWidth;

    @Value("${qr.code.logoHeight}")

    private Integer configLogoHeight;

    @Value("${qr.code.picType}")

    private String configPicType;

    /**

     * 编码
     */
    public static String charset;

    /**

     * 生成二维码的宽
     */
    public static Integer width;

    /**

     * 生成二维码的高
     */
    public static Integer height;

    /**

     * logo的宽
     */
    public static Integer logoWidth;

    /**

     * logo的高
     */
    public static Integer logoHeight;

    /**

     * 生成二维码图片的格式 png, jpg
     */
    public static String picType;

    @PostConstruct

    public void setCharset() {

        charset = this.configCharset;

    }

    @PostConstruct

    public void setWidth() {

        width = this.configWidth;

    }

    @PostConstruct

    public void setHeight() {

        height = this.configHeight;

    }

    @PostConstruct

    public void setLogoWidth() {

        logoWidth = this.configLogoWidth;

    }

    @PostConstruct

    public void setLogoHeight() {

        logoHeight = this.configLogoHeight;

    }

    @PostConstruct

    public void setPicType() {

        picType = this.configPicType;

    }

}

第四步,创建QRCodeUtils工具类,如下

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 com.luoyu.zxing.config.QrCodeConfig;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;

import javax.servlet.ServletOutputStream;

import java.awt.*;

import java.awt.geom.RoundRectangle2D;

import java.awt.image.BufferedImage;

import java.io.File;

import java.util.Hashtable;

@Slf4j

public class QRCodeUtils {

    /**

     * 生成二维码图片
     *
     * @param content      二维码内容
     * @param imgPath      中间log地址
     * @param needCompress 是否压缩
     * @return
     * @throws Exception
     */
    private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
        try {
            Hashtable hints = new Hashtable();

            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            hints.put(EncodeHintType.CHARACTER_SET, QrCodeConfig.charset);

            hints.put(EncodeHintType.MARGIN, 1);

            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QrCodeConfig.width,

                    QrCodeConfig.height, 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;

            }

            // 插入图片

            QRCodeUtils.insertImage(image, imgPath, needCompress);

            return image;

        }catch (Exception e){

            log.error("生成二维码失败:" + e);

            return null;

        }

    }

    /**

     * 插入LOGO
     *
     * @param imgPath      二维码图片
     * @param imgPath      LOGO图片地址
     * @param needCompress 是否压缩
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            log.error(imgPath + ",该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        // 压缩logo
        if (needCompress) {
            if (width > QrCodeConfig.logoWidth) {
                width = QrCodeConfig.logoWidth;
            }
            if (height > QrCodeConfig.logoHeight) {
                height = QrCodeConfig.logoHeight;
            }
            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 = (QrCodeConfig.width - width) / 2;
        int y = (QrCodeConfig.height - 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();
    }

    /**

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

    /**

     * 生成带logo二维码
     *
     * @param content      二维码的内容
     * @param imgPath      中间log地址
     * @param output
     * @param needCompress 是否压缩
     * @throws Exception
     */
    public static void encode(String content, String imgPath, ServletOutputStream output, boolean needCompress) {
        try {
            BufferedImage image = QRCodeUtils.createImage(content, imgPath, needCompress);
            ImageIO.write(image, QrCodeConfig.picType, output);
        } catch (Exception e) {
            log.error("生成二维码失败:" + e);
        }
    }

    /**

     * 生成不带logo二维码
     *
     * @param content 二维码的内容
     * @param output
     * @throws Exception
     */
    public static void encode(String content, ServletOutputStream output) {
        QRCodeUtils.encode(content, null, output, false);
    }

}

第五步,创建QRCodeController类,如下

import com.luoyu.zxing.util.QRCodeUtils;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServletResponse;

import java.io.File;

/**

 * <p>
 * 二维码
 * </p>
 *
 * @author luoyu
 * @since 2018-11-30
 */
@RestController
public class QRCodeController {

    /**

     * 生成普通二维码
     */
    @GetMapping(value = "/qrcode/common")
    public void getCommonQRCode(HttpServletResponse response, String url) throws Exception {
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
            //使用工具类生成二维码
            QRCodeUtils.encode(url, stream);
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }

    /**

     * 生成带有logo二维码
     */
    @GetMapping(value = "/qrcode/logo")
    public void getLogoQRCode(HttpServletResponse response, String url) throws Exception {
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
            // logo 地址
            String logoPath = Thread.currentThread().getContextClassLoader().getResource("").getPath()
                    + "templates" + File.separator + "advator.jpg";
            // String logoPath = "springboot-demo-list/qr-code/src/main/resources/templates/advator.jpg";
            //使用工具类生成二维码
            QRCodeUtils.encode(url, logoPath, stream, true);
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }

}

正文完