Spring Boot Generate QR Code as Base64 String

Tags: zxing generate QR code QR code base64 Spring Boot QR Code Java QR Code

This Java Spring Boot tutorial we learn how to generate QR code as a base64 string in Spring Boot application.

Table of contents

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

Create New Spring Boot Project

Open IntelliJ IDEA, select the menu File > New > Project. (or click on New Project button at IntelliJ Welcome dialog)

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

Spring Boot Generate QR Code as Base64 String

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

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

Spring Boot Generate QR Code as Base64 String

On the Dependencies dialog, click Next button.

Spring Boot Generate QR Code as Base64 String

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

Spring Boot Generate QR Code as Base64 String

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

At this step we implement the service class to generate QR code as a base64 string as following.

Create a new Java package named dev.simplesolution.base64qrcode.service and a new interface named QrCodeService as below Java code.

java/dev/simplesolution/base64qrcode/service/QrCodeService.java

package dev.simplesolution.base64qrcode.service;

public interface QrCodeService {
    String generateQRCodeBase64(String qrCodeContent, int width, int height);
}

Create a new Java package named dev.simplesolution.base64qrcode.service.impl and implement Java class named QrCodeServiceImpl as the Java code below to generate QR code.

java/dev/simplesolution/base64qrcode/service/impl/QrCodeServiceImpl.java

package dev.simplesolution.base64qrcode.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.base64qrcode.service.QrCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

@Service
public class QrCodeServiceImpl implements QrCodeService {

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

    @Override
    public String generateQRCodeBase64(String qrCodeContent, int width, int height) {
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeContent, BarcodeFormat.QR_CODE, width, height);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", byteArrayOutputStream);
            return Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
        } catch (WriterException | IOException e) {
            logger.error(e.getMessage());
        }

        return null;
    }

}

Generate QR Code As Base64 String

At this step we implement a class which use the above service class to generate QR code as base64 string and write it to the log.

Under the dev.simplesolution.base64qrcode package, create a new Java class named TestGenerateQrCode and implement as following Java code.

java/dev/simplesolution/base64qrcode/TestGenerateQrCode.java

package dev.simplesolution.base64qrcode;

import dev.simplesolution.base64qrcode.service.QrCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class TestGenerateQrCode implements CommandLineRunner {

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

    @Autowired
    private QrCodeService qrCodeService;

    @Override
    public void run(String... args) throws Exception {
        String qrCodeContent = "Simple Solution";
        int width = 400;
        int height = 400;
        String qrCodeBase64 = qrCodeService.generateQRCodeBase64(qrCodeContent, width, height);
        logger.info(qrCodeBase64);
    }
}

Complete Application Source Code

Finally we have the complete Spring Boot application which generate base64 QR code as following screenshot.

Spring Boot Generate QR Code as Base64 String

Run Application

Execute the Spring Boot application and observe the log you can see the content of base64 string be printed out as below.

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

2022-03-02 01:05:43.469  INFO 15236 --- [           main] d.s.b.SpringBootBase64QrCodeApplication  : Starting SpringBootBase64QrCodeApplication using Java 1.8.0_231 on SimpleSolution with PID 15236 (D:\SimpleSolution\spring-boot-base64-qr-code\build\classes\java\main started by HP in D:\SimpleSolution\spring-boot-base64-qr-code)
2022-03-02 01:05:43.471  INFO 15236 --- [           main] d.s.b.SpringBootBase64QrCodeApplication  : No active profile set, falling back to 1 default profile: "default"
2022-03-02 01:05:43.787  INFO 15236 --- [           main] d.s.b.SpringBootBase64QrCodeApplication  : Started SpringBootBase64QrCodeApplication in 0.552 seconds (JVM running for 1.956)
2022-03-02 01:05:43.839  INFO 15236 --- [           main] d.s.base64qrcode.TestGenerateQrCode      : iVBORw0KGgoAAAANSUhEUgAAAZAAAAGQAQAAAACoxAthAAABSUlEQVR42u3bMQ6DMAxA0aAOHTlCj9KjtUfrUThCxw4VaRwSElMhgUTjDt8TJLzNMo4Fzu8OB4FAIBAIBAKBQCCHkdGVuMabkx+cf1XLEEh70qerl5De3xO5puUBAjEh95ivifj3fJPTGgKxJaXAQiB/QkrrCYFYE/XU7a09BGJB1CmptKObD1YQyOFkEU9dU7eMoSCQw0msqVJGJZOFhAJ7kY1HJ34t+SGQ35JcU8NTbvJhN0QnF8lDIE3JXFPnTE4kD5ggEAviJZPDwlkyudc309wTArEgTvK1nikFMgUEYkXmGHMmq0YVAmlN1EypVNsY/VoHC4H8miy+7ohPSYEd1977EEgL8v11h7SjXT4yQSCmpB51VjsQiDnxuh3dkskQyPFEv/d9PVOCQGzI4j+LW+pAMxkcBNKa7AgIBAKBQCAQCAQCMSEfG14cCtfHcE8AAAAASUVORK5CYII=

Process finished with exit code 0

Download The Source Code

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

or clone at:

git clone https://github.com/simplesolutiondev/spring-boot-base64-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 Generate QR Code Image Files

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