SoFunction
Updated on 2025-05-13

Detailed steps and complete code for SpringBoot to implement QR code generation

1. Environment construction

  • Development Tools
    • Use mainstream Java development tools such as IntelliJ IDEA or Eclipse, which have good support for Spring Boot, making it easy to create projects, manage dependencies, and run code.
  • JDK environment
    • Make sure that JDK 1.8 or later is installed because the Spring Boot project requires a Java environment to run. You can enter it through the command linejava -versionTo check whether the JDK is installed correctly.

2. Create Spring Boot Project

  • Create a project using Spring Initializr
    • OpenSpring Initializrwebsite.
    • Select the following in the interface:
      • Project: Maven (Maven is recommended as a project management tool)
      • Language:Java
      • Spring Boot Version: Select the latest stable version
      • Dependencies: Add "Spring Web" dependency because we need to generate QR code through the HTTP interface
    • Click the "Generate" button to download the generated project compression package, decompress and import it into the development tool.

3. Introduce QR code generation dependencies

In order to generate QR codes in Spring Boot projects, we need to use a third-party library. Recommended here, it is an open source, powerful QR code generation and parsing library.

  • existAdd dependencies to the file
<dependency>
    <groupId></groupId>
    <artifactId>core</artifactId>
    <version>3.4.1</version>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>javase</artifactId>
    <version>3.4.1</version>
</dependency>
  • Dependency description
    • core: Provides the core functions of QR code generation and analysis.
    • javase: Provides a tool class for operating QR codes in the Java environment.

4. Write QR code to generate code

  • Create a QR code generation service class
    • Create a project namedQrCodeServiceclass, used to encapsulate the logic generated by QR code.
package ;

import ;
import ;
import ;
import ;
import ;
import ;

import ;
import .*;
import ;
import ;
import ;
import ;
import ;

public class QrCodeService {

    /**
      * Generate QR code
      *
      * @param content QR code content
      * @param width QR code width
      * @param height QR code height
      * @param filePath QR code saving path
      * @throws WriterException
      * @throws IOException
      */
    public void generateQRCode(String content, int width, int height, String filePath) throws WriterException, IOException {
        // Set QR code parameters        Map&lt;EncodeHintType, Object&gt; hints = new HashMap&lt;&gt;();
        (EncodeHintType.CHARACTER_SET, "UTF-8"); // Set character encoding        (EncodeHintType.ERROR_CORRECTION, ); // Set fault tolerance level        (, 2); // Set margins
        // Create a QR code generator        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = (content, BarcodeFormat.QR_CODE, width, height, hints);

        // Create a picture        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        ();

        Graphics2D graphics = (Graphics2D) ();
        ();
        (0, 0, width, height);
        ();
        for (int i = 0; i &lt; width; i++) {
            for (int j = 0; j &lt; height; j++) {
                if ((i, j)) {
                    (i, j, 1, 1);
                }
            }
        }

        // Save the picture        File outputFile = new File(filePath);
        (image, "png", outputFile);
    }
}
  • Code description
    • useQRCodeWriterclass to generate QR code.
    • passBitMatrixObject to represent the matrix information of the QR code.
    • useBufferedImageTo create the picture and draw the QR code matrix onto the picture.
    • Finally, useMethod saves the image to the specified path.

5. Create the controller to provide a QR code generation interface

  • createQrCodeControllerkind
    • Create a controller class in the project to receive user requests and call the QR code generation service.
package ;

import ;
import ;
import ;
import ;
import ;

@RestController
public class QrCodeController {

    @Autowired
    private QrCodeService qrCodeService;

    /**
      * Generate QR code interface
      *
      * @param content QR code content
      * @param width QR code width
      * @param height QR code height
      * @param filePath QR code saving path
      * @return
      */
    @GetMapping("/generateQRCode")
    public String generateQRCode(@RequestParam String content, @RequestParam int width, @RequestParam int height, @RequestParam String filePath) {
        try {
            (content, width, height, filePath);
            return "The QR code was generated successfully, and the save path is:" + filePath;
        } catch (Exception e) {
            ();
            return "QR code generation failed:" + ();
        }
    }
}
  • Interface description
    • use@RestControllerThe annotation is marked as the controller class.
    • Define a@GetMappingMethod, receive parameters passed by the user through GET request, including the QR code content, width, height and save path.
    • CallQrCodeServiceofgenerateQRCodeMethod to generate QR code and return the generated result.

6. Test run

  • Start Spring Boot app
    • Run the project in the development tool and start the Spring Boot application.
  • Send a request test
    • Open a browser or use a tool such as Postman to send a request to the interface address, for example:
http://localhost:8080/generateQRCode?content=Hello%20World&width=200&height=200&filePath=D:/
  • If everything is fine, you will see the returned prompt message, such as "QR code generation is successful, the save path is: D:/", and a QR code picture is generated under the specified path.

7. Summary

Through the above steps, we successfully implemented the QR code generation function in the Spring Boot project. From project creation, dependency introduction, service layer code writing to the implementation of controller interface, each step explains the operation method and code implementation in detail. The generated QR code can customize the content, size and saving path according to user needs, and has strong flexibility. This function can be applied to a variety of scenarios, such as activity QR code generation, product QR code generation, etc., providing developers with convenient tools.

The above are the detailed steps and complete codes for SpringBoot to implement QR code generation. For more information about SpringBoot QR code generation, please pay attention to my other related articles!