Spring Boot Read and Decode QR Code Image File

Tags: zxing zxing MultiFormatReader read QR code decode QR code QR code image Spring Boot QR Code Java QR Code Java Read QR Code Spring Boot Read QR Code

In this Spring Boot tutorial we learn how to read and decode a QR code image file in Spring Boot console application with ZXing library.

Table of contents

  1. Create New Spring Boot Console Project
  2. Add ZXing Core and ZXing Java SE Extensions libraries to Spring Boot project
  3. Implement QR Code Service Java Class to Read QR Code File
  4. Read QR Code Image File and Decode the Value
  5. Complete Source Code and Run The Spring Boot Console Application
  6. Download Complete Source Code

Create New Spring Boot Console 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 Read and Decode QR Code Image File - 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-read-qr-code-image-file
  • Type: Gradle
  • Language: Java
  • Version: 1.0.0
  • Name: spring-boot-read-qr-code-image-file
  • Description: Spring Boot Read and Decode QR Code Image File
  • Package: dev.simplesolution.readqrcodeimagefile

Spring Boot Read and Decode QR Code Image File - Create Project

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

Spring Boot Read and Decode QR Code Image File - Create Project

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

Spring Boot Read and Decode QR Code Image File - Create Project

Add ZXing Core and ZXing Java SE Extensions libraries to Spring Boot 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 QR Code Service Java Class to Read QR Code File

Firstly we implement service class to read and decode the content of QR Code Image file using the ZXing library.

Create a new Java package named dev.simplesolution.readqrcodeimagefile.service

Add new Java interface named QRCodeService with source code as below.

java/dev/simplesolution/readqrcodeimagefile/service/QRCodeService.java

package dev.simplesolution.readqrcodeimagefile.service;

import java.io.File;

public interface QRCodeService {
    String readQRCode(File qrCodeFile);
}

Then create a new Java package named dev.simplesolution.readqrcodeimagefile.service.impl

And implement a new Java class named QRCodeServiceImpl as following source code.

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

package dev.simplesolution.readqrcodeimagefile.service.impl;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import dev.simplesolution.readqrcodeimagefile.service.QRCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@Service
public class QRCodeServiceImpl implements QRCodeService {
    private Logger logger = LoggerFactory.getLogger(QRCodeServiceImpl.class);

    @Override
    public String readQRCode(File qrCodeFile) {
        try {
            BufferedImage bufferedImage = ImageIO.read(qrCodeFile);
            BufferedImageLuminanceSource bufferedImageLuminanceSource = new BufferedImageLuminanceSource(bufferedImage);
            HybridBinarizer hybridBinarizer = new HybridBinarizer(bufferedImageLuminanceSource);
            BinaryBitmap binaryBitmap = new BinaryBitmap(hybridBinarizer);
            MultiFormatReader multiFormatReader = new MultiFormatReader();

            Result result = multiFormatReader.decode(binaryBitmap);
            String qrCodeText = result.getText();
            return qrCodeText;
        } catch (IOException | NotFoundException ex) {
            logger.error("Error during reading QR code image", ex);
        }
        return null;
    }
}

Read QR Code Image File and Decode the Value

For example we have a QR code image file at D:\SimpleSolution\qrcode.png as below.

Spring Boot Read and Decode QR Code Image File - Example QR Code

At this step we create a new Java class named TestReadingQRCode which implements CommandLineRunner allow our Spring Boot Console application execute the code to read QR code image file when starting the application.

java/dev/simplesolution/readqrcodeimagefile/TestReadingQRCode.java

package dev.simplesolution.readqrcodeimagefile;

import dev.simplesolution.readqrcodeimagefile.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;

import java.io.File;

@Component
public class TestReadingQRCode implements CommandLineRunner {

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

    @Autowired
    private QRCodeService qrCodeService;

    @Override
    public void run(String... args) throws Exception {
        String qrCodeFilePath = "D:\\SimpleSolution\\qrcode.png";
        File qrCodeFile = new File(qrCodeFilePath);

        String qrCodeContent = qrCodeService.readQRCode(qrCodeFile);
        logger.info("Decoded QR Code Content: " + qrCodeContent);
    }
}

Complete Source Code and Run The Spring Boot Console Application

Finally we have finished implementing the Spring Boot Console Application which reading the QR code image file then decode the value and log it to the console.

The final source code structure as following screenshot.

Spring Boot Read and Decode QR Code Image File - Complete Soure Code

Execute the application to see the content of QR code showing in the console as below.

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

2022-03-25 00:03:56.584  INFO 9408 --- [           main] SpringBootReadQrCodeImageFileApplication : Starting SpringBootReadQrCodeImageFileApplication using Java 1.8.0_231 on SimpleSolution with PID 9408 (D:\SimpleSolution\spring-boot-read-qr-code-image-file\build\classes\java\main started by HP in D:\SimpleSolution\spring-boot-read-qr-code-image-file)
2022-03-25 00:03:56.586  INFO 9408 --- [           main] SpringBootReadQrCodeImageFileApplication : No active profile set, falling back to 1 default profile: "default"
2022-03-25 00:03:56.968  INFO 9408 --- [           main] SpringBootReadQrCodeImageFileApplication : Started SpringBootReadQrCodeImageFileApplication in 0.646 seconds (JVM running for 2.208)
2022-03-25 00:03:57.037  INFO 9408 --- [           main] d.s.r.TestReadingQRCode                  : Decoded QR Code Content: https://simplesolution.dev

Download Complete Source Code

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

or clone at:

git clone https://github.com/simplesolutiondev/spring-boot-read-qr-code-image-file.git

or download at:

Download Source Code

Happy Coding 😊

Spring Boot Restful API Generate QR Code as Base64 String

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