QR code application practice: perfect combination of Spring Boot and ZXing

: Just work hard and leave the rest to time

: Xiaopozhan

QR code application practice: the perfect combination of Spring Boot and ZXing

  • Preface
  • First: Introducing QR Codes and ZXing
  • Second: springboot integrates zxing
    • Add ZXing dependency
    • Generate QR code
    • Generate barcode

Foreword

In the digital age, QR codes have become a common way of exchanging information. They are used in a wide range of applications, from product labels to event flyers, and electronic payments. This article will show you how to integrate the ZXing library in a Spring Boot application to create and parse QR codes. Whether you want to add QR code functionality to your products or scan functionality to your mobile app, this blog will provide you with a clear guide.

First: Introduction to QR codes and ZXing

QR code, full name Quick Response code, is a type of 2D barcode that was first developed in 1994 by the Japanese company Denso Wave. It is a matrix 2D barcode capable of storing various data types, usually presented as a black module and a white background. QR codes can store text, URL, contact information, geographical location and other information, so they are widely used in mobile devices, advertising communication, product identification and other fields.

ZXing, whose full name is “Zebra Crossing”, is an open source Java library used for QR code generation and parsing. It is a powerful tool that can be used to generate QR codes and parse multiple QR code formats including QR codes. ZXing provides APIs in multiple programming languages, allowing developers to easily integrate QR code functions into their applications. It supports multiple platforms, including Android, iOS, Java, etc. In addition to QR codes, ZXing also supports parsing other one-dimensional and two-dimensional codes, such as EAN, UPC, DataMatrix, etc.

Using the ZXing library, you can easily integrate QR code functionality into your software development projects, whether generating QR codes for sharing or parsing QR codes to obtain the information within them. In actual use, you can add comments to explain key parts of the code to help other developers understand your implementation. This is very helpful for team collaboration and maintaining code.

Second: springboot integrates zxing

Add ZXing dependency

It is very simple to add a dependency on the ZXing library in the pom.xml file of your Maven project. You can add the following ZXing dependencies within the tag:

<dependencies>
    <!-- Other dependencies -->
    <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>core</artifactId>
        <version>3.4.1</version> <!-- Please use the latest version -->
    </dependency>
</dependencies>

Please note that the version part of the above example can use a specific version of ZXing based on your project needs. It is recommended to use the latest version to get the latest features and improvements.

After adding this dependency, Maven will automatically download and add the ZXing library to your project. You can then use the ZXing library in your Java code to generate and parse QR codes. Don’t forget to add comments to your code to help other developers understand your implementation.

Generate QR code

The following is an example Java service class, which contains a method for generating QR codes, implemented using the ZXing library. I’ll detail the relevant parameters to help you understand the code:

package com.todoitbo.baseSpringbootDasmart.csdn;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class QRCodeGeneratorService {<!-- -->
    // Method to generate QR code
    public void generateQRCode(String data, int width, int height, String filePath) {<!-- -->
        try {<!-- -->
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // Set character encoding
            hints.put(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.H); // Error correction level
            hints.put(EncodeHintType.MARGIN, 1); // QR code margin

            MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix bitMatrix = writer.encode(data, BarcodeFormat.QR_CODE, width, height, hints);

            //Create a BufferedImage object to represent the QR code
            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) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
                }
            }

            // Save QR code to file
            File qrCodeFile = new File(filePath);
            ImageIO.write(image, "png", qrCodeFile);

            System.out.println("QR code has been generated and saved to: " + filePath);
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {<!-- -->
        QRCodeGeneratorService qrCodeGenerator = new QRCodeGeneratorService();
        String data = "https://todoitbo.fun"; // Data to be stored in the QR code
        int width = 300; //Width of QR code
        int height = 300; //Height of QR code
        String filePath = "qrcode.png"; // Path to the generated QR code file

        qrCodeGenerator.generateQRCode(data, width, height, filePath);
    }
}

In the above code, the generateQRCode method accepts four parameters:

  1. data: The data to be stored in the QR code, which can be text, URL, etc.
  2. width: The width of the QR code (pixels).
  3. height: The height of the QR code (pixels).
  4. filePath: The saving path of the generated QR code file.

The method uses the MultiFormatWriter of the ZXing library to generate a QR code and save the QR code to a file in the specified path. Make sure to modify these parameters according to your needs to generate the QR code you want. At the same time, comments should be added to the actual code to help other developers understand this QR code generation service.

Generate barcode

If you want to generate barcodes, you can use the ZXing library to do so. The following is an example Java service class, which contains methods for generating barcodes and details the relevant parameters:

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.common.BitMatrix;

public class BarcodeGeneratorService {<!-- -->
    //Method to generate barcode
    public void generateBarcode(String data, int width, int height, String filePath) {<!-- -->
        try {<!-- -->
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // Set character encoding

            MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix bitMatrix = writer.encode(data, BarcodeFormat.CODE_128, width, height, hints);

            // Create a BufferedImage object to represent the barcode
            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) ? 0 : 0xFFFFFF); // Generate a barcode with black bars and white background
                }
            }

            // Save barcode to file
            File barcodeFile = new File(filePath);
            ImageIO.write(image, "png", barcodeFile);

            System.out.println("Barcode has been generated and saved to: " + filePath);
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {<!-- -->
        BarcodeGeneratorService barcodeGenerator = new BarcodeGeneratorService();
        String data = "123456789"; // Data to be stored in the barcode
        int width = 200; //Width of barcode
        int height = 100; //Height of barcode
        String filePath = "barcode.png"; // Path to the generated barcode file

        barcodeGenerator.generateBarcode(data, width, height, filePath);
    }
}

In the above code, the generateBarcode method accepts four parameters:

  1. data: The data to be stored in the barcode, which can be product barcodes, etc.
  2. width: The width of the barcode (pixels).
  3. height: The height of the barcode (pixels).
  4. filePath: The saving path of the generated barcode file.

The method uses the MultiFormatWriter of the ZXing library to generate a barcode and save the barcode to a file in the specified path. Make sure to modify these parameters according to your needs to generate the barcodes you want. At the same time, comments should be added to the actual code to help other developers understand this barcode generation service.