How to Generate QR Codes in Java with Spring Boot.

Daniel Angel
5 min readMar 12, 2023

--

QR codes have become a popular way to store and share information. They can be used for a variety of purposes, such as storing URLs, contact information, or even payment details. In this article, we will see how to generate QR codes using Zxing, Java and Spring Boot in the easiest and fastest way.

qr-code-codereview

Step 1: Setting Up Your Environment

Before we can start generating QR codes, we need to set up our environment. Here are the tools we’ll be using:

  • Java Development Kit (JDK) 8 or higher
  • Spring Boot 2.4.2 or higher
  • Maven 3.6.3 or higher

Once you’ve installed these tools, you can create a new Spring Boot project using the Spring Initializr. Make sure to select the following dependencies:

  • Spring Web
  • Spring Boot DevTools
  • Zxing

Once you’ve generated your project you’re ready to start generating and and customize QR codes!

Step 2: Adding QR Code Generation Functionality

To generate QR codes, we’ll be using the Zxing library, which is a popular open-source library for generating and reading QR codes. We’ll add this library to our project by adding the following dependency to our pom.xml file:

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

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

Step 3: Adding QR Code controller

Next, we’ll create a new controller class that will handle our QR code generation requests. Here’s an example:

@RestController
public class QRCodeController {

@Autowired
private QRCodeService qrCodeService;

@GetMapping("/v1/qrcode")
public void generateQRCode(HttpServletResponse response,
@RequestParam String text,
@RequestParam(defaultValue = "350") int width,
@RequestParam(defaultValue = "350") int height) throws Exception {
BufferedImage image = qrCodeService.generateQRCode(text, width, height);
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(image, "png", outputStream);
outputStream.flush();
outputStream.close();
}
}

In this controller, we have added an instance of QRCodeService using the @Autowired annotation. Within the generateQRCode method, we are using this instance to generate the QR code. Then, we are typing the QR code image into the response output stream.

We also add the parameters of enter as textthat will be what we will add in our QR code to be read and the size of these with widthand height.

Step 4: Adding QR Code Generation Service

Next, we will create a QRCodeService class to handle the logic of generating the QR code. We will use the BitMatrix class from ZXing to generate the QR code as a BufferedImage.

@Service
public class QRCodeService {

public BufferedImage generateQRCode(String text, int width, int height) throws Exception {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
}

In the above code, we have created a method generateQRCode that takes in three parameters: text, width, and height. The data parameter represents the data that we want to encode as a QR code, while the width and height parameters represent the size of the QR code.

We have used the QRCodeWriter class from ZXing to encode the data as a QR code. We pass in the BarcodeFormat.QR_CODE parameter to specify that we want to generate a QR code. We then use the MatrixToImageWriter class to convert the BitMatrix into a BufferedImage.

BarcodeFormat.QR_CODE is an enumeration constant defined in the ZXing library that represents the QR code format for encoding data as a two-dimensional matrix barcode.

  • UPC_A: UPC-A barcode format for encoding 12-digit UPC codes used in retail.
  • EAN_13: EAN-13 barcode format for encoding 13-digit European Article Numbers (EAN) used in retail.
  • CODE_39: Code 39 barcode format for encoding alphanumeric characters.
  • DATA_MATRIX: Data Matrix barcode format for encoding small amounts of data in a square matrix.
  • PDF_417: PDF-417 barcode format for encoding large amounts of data in a two-dimensional barcode.
  • CODABAR: Codabar barcode format for encoding numbers and certain special characters.

These are just a few of the many barcode formats that are supported by the ZXing library. Depending on your use case, you may need to use a different barcode format to encode your data.

Step 5: We tested our API

To test our Api we can use a web browser or a tool like Postman to send an HTTP GET request to the /v1/qrcode URL with the data parameter set to the data we want to encode as a QR code.

For example, if we want to generate a QR code for the URL https://www.google.com, we can send an HTTP GET request to http://localhost:8080/v1/qrcode?text=https://www.google.com.

If everything is working correctly, we should see a PNG image containing the QR code in our browser or in the response body of our HTTP client.

Testing in postman

Remember that you can modify the size of the image as necessary

Suggested improvements

  • Now that we’ve created the basic functionality for generating QR codes, there are several improvements we could make to make it even better. Here are some suggestions:
  • Add authentication and authorization: If you plan to use QR code generation in a production app, it’s important to make sure that only authorized people can generate QR codes.
  • Store the generated QR codes: If you want to track the generated QR codes and the use given to them, you can store them in a database or in a cloud storage system. This can also be useful if you want to provide a way to download the generated QR codes in the future.
  • Customize QR code image: The zxing library provides several customization options for QR codes, such as changing the background color or adding a logo. You can experiment with these options to create QR codes that best suit your brand or app.

for example:

 // specify the configuration for the color of the generated image
MatrixToImageConfig config = new MatrixToImageConfig(
0xFF000000, // black foreground
0xFFF5DEB3 // beige background
);

// create the buffered image from the QR code
BufferedImage qrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix, config);

Conclusion

In this tutorial, we have learned how to generate QR codes using Java and Spring Boot. We’ve used the Zxing library to encode data as a QR code and created a Spring Boot handler to handle HTTP requests and generate QR codes. In addition, we have separated the logic of generating the QR code from the controller to make our code more modular.

QR codes can be used for a wide range of applications such as URL sharing, contact information and these can be of different types depending on the data types. By using Java and Spring Boot we can easily generate QR codes in our web applications and provide a more convenient and secure way to share information with our users.

--

--

Daniel Angel

Backend developer | Java, Spring boot, Cloud| Laravel, Php