Spring Boot Restful API Generate QR Code as Base64 String

Tags: zxing zxing QRCodeWriter generate QR code QR code base64 Base64 QR Code Spring Boot QR Code Java QR Code Rest API QR Code

In this Java Spring Boot tutorial we learn how to implement a Spring Boot Restful API application which generate QR code as a Base64 String using ZXing Core and ZXing Java SE Extensions libraries.

Table of contents

  1. Create New Spring Boot Restful API Project to Generate Base64 QR Code
  2. Add ZXing Core and ZXing Java SE Extensions libraries to Spring Boot Restful API project
  3. Implement Java Service Class to Generate Base64 QR Code
  4. Implement RestController Class to Generate Base64 QR Code
  5. Complete Source Code and Running Restful API Application
  6. Download Complete Source Code

Create New Spring Boot Restful API Project to Generate Base64 QR Code

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 Restful API Generate QR Code as Base64 String - Create Project

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

  • Group: dev.simplesolution
  • Artifact: spring-boot-rest-qr-code-base64
  • Type: Gradle
  • Language: Java
  • Version: 1.0.0
  • Name: spring-boot-rest-qr-code-base64
  • Description: Spring Boot Restful API Generate QR Code as Base64 String
  • Package: dev.simplesolution.restqrcodebase64

Spring Boot Restful API Generate QR Code as Base64 String - Create Project

On the Dependencies dialog, select below dependencies and click Next button.

  • Spring Web

Spring Boot Restful API Generate QR Code as Base64 String - Create Project

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

Spring Boot Restful API Generate QR Code as Base64 String - Create Project

Add ZXing Core and ZXing Java SE Extensions libraries to Spring Boot Restful API project

To generate the QR code image we use the ZXing Core and ZXing Java SE Extensions libraries.

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 Java Service Class to Generate Base64 QR Code

Create a new Java package named dev.simplesolution.restqrcodebase64.service and create a new Java interface named QRCodeService as the source code below.

java/dev/simplesolution/restqrcodebase64/service/QRCodeService.java

package dev.simplesolution.restqrcodebase64.service;

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

Then implement a new class to generate Base64 QR code string using the Zxing library as below.

Create a new Java package named dev.simplesolution.restqrcodebase64.service.impl

Add new Java class named QRCodeServiceImpl as following source code.

java/dev/simplesolution/restqrcodebase64/service/impl/QRCodeServiceImpl.java

package dev.simplesolution.restqrcodebase64.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.restqrcodebase64.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);
            String qrCodeBase64 = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
            return qrCodeBase64;
        } catch (WriterException ex) {
            logger.error("Error during generate QR Code", ex);
        } catch (IOException ex) {
            logger.error("Error during generate QR Code", ex);
        }
        return null;
    }
}

Implement RestController Class to Generate Base64 QR Code

At this step we implement a new RestController class which expose an endpoint to generate and return QR code in Base64 String format.

Create a new Java package named dev.simplesolution.restqrcodebase64.controller

Implement a new Java class named QRCodeController as following source code.

java/dev/simplesolution/restqrcodebase64/controller/QRCodeController.java

package dev.simplesolution.restqrcodebase64.controller;

import dev.simplesolution.restqrcodebase64.service.QRCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class QRCodeController {
    private static final int WIDTH = 500;
    private static final int HEIGHT = 500;

    @Autowired
    private QRCodeService qrCodeService;

    @GetMapping("/generate-qr-code-base64")
    public ResponseEntity<String> generateQRCodeBase64() {
        String contentToGenerateQrCode = "Simple Solution";
        String qrCodeBase64 = qrCodeService.generateQRCodeBase64(contentToGenerateQrCode, WIDTH, HEIGHT);
        return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(qrCodeBase64);
    }
}

Complete Source Code and Running Restful API Application

Finally we have finished the Restful API to generate Base64 QR Code with the complete source code structure as below screenshot.

Spring Boot Restful API Generate QR Code as Base64 String - Complete Source Code

Run the Spring Boot Restful API application and access the link http://localhost:8080/generate-qr-code-base64 on your browser to see the response body with Base64 String as below screenshot.

Spring Boot Restful API Generate QR Code as Base64 String - Result

Download Complete Source Code

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

or clone at:

git clone https://github.com/simplesolutiondev/spring-boot-rest-qr-code-base64.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 as Base64 String

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