Add dependencies
<!-- ZXing Core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.1</version>
</dependency>
<!-- ZXing Java SE -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.1</version>
</dependency>
A QR Generator class
package com.example.qr_generator.util;
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 java.io.ByteArrayOutputStream;
import java.io.IOException;
public class QRCodeGenerator {
public static byte[] generateQRCodeImage(String text, int width, int height) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
try (ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream()) {
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
return pngOutputStream.toByteArray();
}
}
}
Controller and business logic
package com.example.qr_generator.controller;
import com.example.qr_generator.util.QRCodeGenerator;
import com.google.zxing.WriterException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
@RestController
@RequestMapping("/api")
@Slf4j
public class QRController {
@GetMapping(value = "/qr", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<byte[]> generateQRCode(@RequestParam("url") String url) {
try {
// Generate a 250x250 QR code image for the provided URL
byte[] qrImage = QRCodeGenerator.generateQRCodeImage(url, 250, 250);
return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(qrImage);
} catch (WriterException | IOException e) {
log.error("Failed to generate QR code message: {}, rootCause: ", e.getMessage(), e.getCause());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}