Spring Boot 3 REST API — Barcode and QR Code Generation

In this post, we’ll learn how to generate barcodes and QR codes and expose them as an endpoint in the Spring Boot API.

· Prerequisites
· Overview
∘ Barcodes
∘ QR Codes
· Getting Started
∘ Add Dependencies
∘ Create a Service for Barcode and QR Code Generation
∘ Create a REST Controller
· Test the REST APIs
∘ Generate a QR Code
∘ Generate a Barcode
· Conclusion
· References


Prerequisites

This is the list of all the prerequisites:

  • Spring Boot 3+
  • Maven 3.6.3
  • Java 21
  • Postman / insomnia or any other API testing tool.

Overview

Barcodes

barcode or bar code is a method of representing data in a visual, machine-readable form. Initially, barcodes represented data by varying the widths, spacings, and sizes of parallel lines.

https://en.wikipedia.org/wiki/Barcode

Types of Barcodes

1D Barcodes (Linear Barcodes): These are the traditional barcodes with parallel lines. They represent data using the width and spacing of the bars. Examples include:

  • UPC (Universal Product Code): Used on most retail products.
  • EAN (European Article Number): Similar to UPC, used internationally.
  • Code 39: Often used in automotive and defense industries.
  • Code 128: Used for shipping labels and packaging.

QR Codes

QR code, quick-response code,[1] is a type of two-dimensional matrix barcode invented in 1994 by Masahiro Hara of Japanese company Denso Wave for labelling automobile parts.

Structure of QR Codes

  • 2D Barcodes: QR codes (Quick Response codes) are two-dimensional codes with black squares arranged on a white grid. They can store significant data, including URLs, text, and other information.

How QR Codes Work

  • Data Encoding: QR codes can encode various data types, including numeric, alphanumeric, binary, and Kanji characters. The data is converted into a binary format and then represented as a pattern of squares.
  • QR Code Generation: QR code generation software converts the encoded data into a visual QR code format. It can be used with various libraries or online tools.
  • Printing: The generated QR code can be printed on labels, packaging, or displayed on screens.
  • A QR code scanner (often a smartphone camera or a dedicated QR code reader) captures the image of the QR code.
  • The scanner analyzes the pattern of squares and converts it into a binary format.
  • The binary data is then decoded back into the original information.
  • Data Retrieval: The decoded data can be used to perform various actions, such as opening a URL in a web browser, displaying text, or adding a contact to a phone.

Getting Started

Let’s create a simple Spring Boot project from start.spring.io, with the following dependencies: Spring Web.

Add Dependencies

We’ll use the ZXing library for 1D Barcode and QR Code Generation.

Add the necessary dependencies for barcode and QR code generation to your pom.xml

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

Create a Service for Barcode and QR Code Generation

Create a service class to handle barcode and QR code generation.

@Service
public class BarcodeServiceImpl implements BarcodeService {

private static final String DEFAULT_IMAGE_FORMAT = "png";

@Override
public byte[] generateQRCode(String text) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, 400, 400);

var qrcodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
ImageIO.write(qrcodeImage, DEFAULT_IMAGE_FORMAT, pngOutputStream);

return pngOutputStream.toByteArray();
}

@Override
public byte[] generateBarcode(String text) throws IOException, WriterException {
var height = 200;
var width = 400;
EnumMap<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix bitMatrix = writer.encode(text, BarcodeFormat.EAN_13, width, height, hints);

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0 : 0xFFFFFF);
}
}

ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, DEFAULT_IMAGE_FORMAT, pngOutputStream);

return pngOutputStream.toByteArray();
}

}

Create a REST Controller

Finally, we create a controller that exposes endpoints for generating barcodes and QR codes.

@RestController
@RequestMapping(value = "/api")
public class BarcodeController {

private final BarcodeService barcodeService;

public BarcodeController(BarcodeService barcodeService) {
this.barcodeService = barcodeService;
}

@GetMapping(value = "/{type}", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<byte[]> generateCode(@PathVariable String type, @RequestParam String text) {
byte[] code;
try {
return switch (type.toLowerCase()) {
case "qrcode" -> {
code = barcodeService.generateQRCode(text);
yield ResponseEntity.ok(code);
}
case "barcode" -> {
code = barcodeService.generateBarcode(text);
yield ResponseEntity.ok(code);
}
default -> ResponseEntity.badRequest().body(null); // 400 Bad Request for invalid type
};
} catch (WriterException | IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
}

Test the REST APIs

Generate a QR Code

  • URLhttp://localhost:8080/api/qrcode?text=helloword
  • MethodGET
  • Response: A PNG image of the QR code.

Generate a Barcode

  • URLhttp://localhost:8080/api/barcode?text=6923450657713
  • MethodGET
  • Response: A PNG image of the barcode

Conclusion

Well done! In this post, we learned how to generate barcodes and QR codes in a Spring Boot 3 REST API and expose them via endpoints.

The complete source code is available on GitHub.

Support me through GitHub Sponsors.

Thank you for reading!! See you in the next post.

References

👉 Link to Medium blog

Related Posts