Spring Boot Generate QR Code Image Files

Tags: zxing generate QR code zxing QRCodeWriter QR code generator Spring Boot QR Code Java QR Code

This Spring Boot tutorial we learn how to implement Spring Boot application to generate QR code image files.

Table of contents

  1. Create New Spring Boot Project
  2. Add ZXing dependencies to the Spring Boot Project
  3. Implement QR Code Generator Service Class
  4. Generate QR Code Image Files
  5. Complete Application Source Code
  6. Run Application
  7. Download Source Code

Create New Spring Boot Project

Open IntelliJ IDEA, select the menu File > New > Project.

On the New Project dialog, select Spring Initializr and click Next button.

Spring Boot Generate QR Code Image Files

On the Spring initializr Project Settings dialog input the new project information as below and click Next button.

  • Group: dev.simplesolution
  • Artifact: spring-boot-generate-qr-code
  • Type: Gradle
  • Version: 1.0.0
  • Name: spring-boot-generate-qr-code
  • Description: Spring Boot Generate QR Code
  • Package: dev.simplesolution.qrcode

Spring Boot Generate QR Code Image Files

On the Dependencies dialog, click Next button.

Spring Boot Generate QR Code Image Files

Select the location for your project and click Finish button to create new Spring Boot project.

Spring Boot Generate QR Code Image Files

Add ZXing dependencies to the Spring Boot Project

To generate the QR code image we use the ZXing library.

To use ZXing library in the Gradle project, add the following dependency to the build.gradle file.

implementation group: 'com.google.zxing', name: 'core', version: '3.4.1'

implementation group: 'com.google.zxing', name: 'javase', version: '3.4.1'

If you are using Maven build, add the following dependency to the pom.xml file.

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.4.1</version>
</dependency>

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.4.1</version>
</dependency>

Implement QR Code Generator Service Class

At this step we implement Java QR code generator class to generate QR code file from a given content.

Create a new package named dev.simplesolution.qrcode.service and a new interface QrCodeGeneratorService as below.

src/main/java/dev/simplesolution/qrcode/service/QrCodeGeneratorService.java

package dev.simplesolution.qrcode.service;

public interface QrCodeGeneratorService {
    boolean generateQRCode(String qrCodeContent, String filePath, int width, int height);
}

Adding a new package named dev.simplesolution.qrcode.service.impl and implement a new Java class named QrCodeGeneratorServiceImpl as the source code below.

In this class we implement a method which arguments are the content to encode to the QR code file, the file path to save QR code file and QR code width, height.

src/main/java/dev/simplesolution/qrcode/service/impl/QrCodeGeneratorServiceImpl.java

package dev.simplesolution.qrcode.service.impl;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import dev.simplesolution.qrcode.service.QrCodeGeneratorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class QrCodeGeneratorServiceImpl implements QrCodeGeneratorService {

    private Logger logger = LoggerFactory.getLogger(QrCodeGeneratorServiceImpl.class);

    @Override
    public boolean generateQRCode(String qrCodeContent, String filePath, int width, int height) {
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeContent, BarcodeFormat.QR_CODE, width, height);
            Path path = Paths.get(filePath);
            MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
            return true;
        } catch (WriterException e) {
            logger.error("Error", e);
        } catch (IOException e) {
            logger.error("Error", e);
        }
        return false;
    }

}

Generate QR Code Image Files

Under the resources directory add the following configuration to application.properties file to configure the directory where QR code be saved.

src/main/resources/application.properties

qr.code.directory=D:\\SimpleSolution\\Data\\

And implement a new Java class named TestGenerateQrCode as below source code.

In this class we loop from one to five and generate five QR image files and save it to the configured directory before. The class also implements CommandLineRunner to execute the code when the Spring Boot application get started.

src/main/java/dev/simplesolution/qrcode/TestGenerateQrCode.java

package dev.simplesolution.qrcode;

import dev.simplesolution.qrcode.service.QrCodeGeneratorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class TestGenerateQrCode implements CommandLineRunner {

    private Logger logger = LoggerFactory.getLogger(TestGenerateQrCode.class);

    @Value("${qr.code.directory}")
    private String qrCodeDirectory;

    @Autowired
    private QrCodeGeneratorService qrCodeGeneratorService;

    @Override
    public void run(String... args) throws Exception {
        for(int i = 1; i <= 5; i++) {
            String filePath = qrCodeDirectory + i + ".png";
            String qrCodeContent = "Simple Solution " + i;
            int width = 400;
            int height = 400;
            boolean result = qrCodeGeneratorService.generateQRCode(qrCodeContent, filePath, width, height);
            if(result) {
                logger.info("Generate QR code file " + filePath + " successfully");
            }
        }
    }
}

Complete Application Source Code

At this step we have final Spring Boot application with source code structure as the screenshot below.

Spring Boot Generate QR Code Image Files

Run Application

Execute the Spring Boot application.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.2)

2022-01-09 22:26:30.893  INFO 17716 --- [           main] .s.q.SpringBootGenerateQrCodeApplication : Starting SpringBootGenerateQrCodeApplication using Java 1.8.0_231 on SimpleSolution with PID 17716 (D:\SimpleSolution\spring-boot-generate-qr-code\build\classes\java\main started by SS in D:\SimpleSolution\spring-boot-generate-qr-code)
2022-01-09 22:26:30.895  INFO 17716 --- [           main] .s.q.SpringBootGenerateQrCodeApplication : No active profile set, falling back to default profiles: default
2022-01-09 22:26:31.268  INFO 17716 --- [           main] .s.q.SpringBootGenerateQrCodeApplication : Started SpringBootGenerateQrCodeApplication in 0.648 seconds (JVM running for 1.964)
2022-01-09 22:26:31.328  INFO 17716 --- [           main] d.s.qrcode.TestGenerateQrCode            : Generate QR code file D:\SimpleSolution\Data\1.png successfully
2022-01-09 22:26:31.337  INFO 17716 --- [           main] d.s.qrcode.TestGenerateQrCode            : Generate QR code file D:\SimpleSolution\Data\2.png successfully
2022-01-09 22:26:31.347  INFO 17716 --- [           main] d.s.qrcode.TestGenerateQrCode            : Generate QR code file D:\SimpleSolution\Data\3.png successfully
2022-01-09 22:26:31.355  INFO 17716 --- [           main] d.s.qrcode.TestGenerateQrCode            : Generate QR code file D:\SimpleSolution\Data\4.png successfully
2022-01-09 22:26:31.367  INFO 17716 --- [           main] d.s.qrcode.TestGenerateQrCode            : Generate QR code file D:\SimpleSolution\Data\5.png successfully

Process finished with exit code 0

After the application execute success we have the QR code file be generated in configured directory as below screenshot.

Spring Boot Generate QR Code Image Files

Download The Source Code

The source code in this article can be found at: github.com/simplesolutiondev/spring-boot-generate-qr-code

or clone at:

git clone https://github.com/simplesolutiondev/spring-boot-generate-qr-code.git

or download at:

Download Source Code

Happy Coding 😊

Spring Boot Web Generate and Display QR Code as Base64 String

Spring Boot Rest API Generate QR Code

Spring Boot Web Upload and Read QR Code Image

Spring Boot Web Generate and Display QR Code

Read QR Code from Image File or Base64 String in Java using ZXing

Generate QR Code in Java using ZXing

Spring Boot Generate QR Code as Base64 String