Generate QR code with Spring Boot+ZXing

Posted by nathanmaxsonadil on Tue, 08 Feb 2022 01:53:57 +0100

1. Introduction to ZXing
Zxing is an open source, multi format 1D/2D barcode image processing library implemented in Java. It contains ports to connect with other languages. Zxing can use the built-in camera of the mobile phone to scan and decode the bar code.

2. Understand QR Code:
QR Code is also called two-dimensional Bar Code. The common two-dimensional code is QR Code. QR full name is Quick Response. It is a super popular coding method on mobile devices in recent years. It can store more information and represent more data types than the traditional Bar Code bar code.
Two dimensional bar code (2-dimensional bar code) is a black-and-white graphic recording data symbol information distributed in a plane (two-dimensional direction) according to a certain law with a specific geometric figure; In coding, the concepts of "0" and "1" bit streams that form the internal logic basis of the computer are skillfully used, and several geometric shapes corresponding to binary are used to represent literal and numerical information, Automatic information processing is realized by automatic reading through image input equipment or photoelectric scanning equipment: it has some commonalities of bar code technology: each code system has its specific character set; Each character has a certain width; It has certain verification function, etc. At the same time, it also has the function of automatically identifying the information of different peers and processing the rotation change points of graphics.

3. How to generate QR code
The generation basis of QR code is zxing package, which is an open source package of Google. We need to use the original zxing method to realize it.
Add dependency

<!-- QR code support package -->
<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>

Then write the method of generating QR code in the tool class and call it when we use it

Tool class codes are as follows:

public class QRCodeUtil {
   private static final String CHARSET = "utf-8";
   private static final String FORMAT_NAME = "JPG";
   // QR code size
   private static final int QRCODE_SIZE = 300;


/**
 * Generate QR code image
 * @param content QR code content
 * @param imgPath Picture address
 * @param needCompress Whether to compress
 * @return
 * @throws Exception
 */
private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {

    Hashtable hints = new Hashtable();
    //The order of fault tolerance level from large to small: l > m > Q > H
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
    hints.put(EncodeHintType.MARGIN, 1);
    //Generate QR code
    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;
    }

    return image;
}



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);
 }

public static void encode(String content, OutputStream output) throws Exception {
    QRCodeUtil.encode(content, null, output, false);
 }

}

Call tool class:

@RestController
public class QRCodeTestController {
/**
 * Generate ordinary QR code according to url
 */
@RequestMapping(value = "/createCommonQRCode")
public void createCommonQRCode(HttpServletResponse response, String url) throws Exception {
    ServletOutputStream stream = null;
    try {
        stream = response.getOutputStream();
        //Use tool class to generate QR code
        QRCodeUtil.encode(url, stream);
    } catch (Exception e) {
        e.getStackTrace();
    } finally {
        if (stream != null) {
            stream.flush();
            stream.close();
        }

    }
 }
}

The url is the link of the web page. We only need to pass the parameters here to automatically generate the QR code.
The generated QR code is shown in the figure below:

Topics: Java