SpringBoot中生成二維碼的案例分享
引言
在Spring Boot項(xiàng)目中整合ZXing庫來生成二維碼是一個(gè)常見的需求。
zxing,全稱"Zebra Crossing",是一個(gè)功能強(qiáng)大的開源Java庫,專門用于二維碼的生成與解析。它不僅能夠生成QR碼,還能解析包括QR碼在內(nèi)的多種二維碼格式。ZXing提供了多語言API,使得開發(fā)者能夠輕松地將二維碼功能集成到各種應(yīng)用中。它支持Android、iOS、Java等多個(gè)平臺,并且除了QR碼,還能解析其他一維碼和二維碼,如EAN、UPC、DataMatrix等。
1. 添加zxing庫的依賴
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.2</version>
</dependency>
2. 生成二維碼
創(chuàng)建一個(gè)SpringBoot服務(wù)類QRCodeService,用于生成二維碼圖片:
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
@Service
public class QRCodeService {
public void generateQRCodeImage(String text, int width, int height, String filePath)
throws IOException {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
}
3. 調(diào)用二維碼服務(wù)
3.1 將二維碼圖拍你保存
最后在SpringBoot的Controller中調(diào)用這個(gè)服務(wù):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
public class QRCodeController {
@Autowired
private QRCodeService qrCodeService;
@GetMapping("/generateQRCode")
public String generateQRCode(@RequestParam String text, @RequestParam int width, @RequestParam int height) {
try {
qrCodeService.generateQRCodeImage(text, width, height, "myqrcode.png");
return "QR Code generated successfully!";
} catch (IOException e) {
return "QR Code generation failed: " + e.getMessage();
}
}
}
當(dāng)訪問/generateQRCode端點(diǎn)并傳遞text、width和height參數(shù)時(shí),它將生成一個(gè)名為myqrcode.png的二維碼圖片并保存到項(xiàng)目根目錄下。
http://localhost:8080/generateQRCode?text=Hello,World!&width=350&height=350
3.2 直接返回二維碼圖片
修改QRCodeController來返回二維碼圖片:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
@RestController
public class QRCodeController {
@GetMapping("/generateQRCode")
public ResponseEntity<Resource> generateQRCode(@RequestParam String text, @RequestParam Integer width, @RequestParam Integer height) throws IOException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, getHints());
BufferedImage qrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(qrCodeImage, "PNG", byteArrayOutputStream);
byte[] qrCodeBytes = byteArrayOutputStream.toByteArray();
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE);
return ResponseEntity.ok()
.headers(headers)
.contentLength(qrCodeBytes.length)
.body(new ByteArrayResource(qrCodeBytes));
}
private Map<EncodeHintType, Object> getHints() {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
return hints;
}
}
generateQRCode先生成二維碼的BitMatrix,然后轉(zhuǎn)換為BufferedImage,以便獲取二維碼圖片的字節(jié)流。
3.2 注冊BufferedImage消息轉(zhuǎn)換器返回圖片
3.2中返回圖片也可以通過注冊一個(gè)SpringBoot的消息轉(zhuǎn)換器來實(shí)現(xiàn):
@Bean
public HttpMessageConverter<BufferedImage> createImageHttpMessageConverter() {
return new BufferedImageHttpMessageConverter();
}
返回圖片
package com.example.demo.controller;
import java.awt.image.BufferedImage;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
@RestController
@RequestMapping("/qr")
public class QrCodeController {
@GetMapping(value = "/{barcode}", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<BufferedImage> barbecueEAN13Barcode(@PathVariable("barcode") String barcode)
throws Exception {
QRCodeWriter barcodeWriter = new QRCodeWriter();
BitMatrix bitMatrix =
barcodeWriter.encode(barcode, BarcodeFormat.QR_CODE, 200, 200);
return new ResponseEntity<>(MatrixToImageWriter.toBufferedImage(bitMatrix),HttpStatus.OK);
}
}
現(xiàn)在,當(dāng)訪問/qr端點(diǎn)時(shí),將直接收到一個(gè)二維碼圖片作為響應(yīng)。

到此這篇關(guān)于SpringBoot中生成二維碼的案例分享的文章就介紹到這了,更多相關(guān)SpringBoot生成二維碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java concurrency之CountDownLatch原理和示例_動力節(jié)點(diǎn)Java學(xué)院整理
CountDownLatch是一個(gè)同步輔助類,在完成一組正在其他線程中執(zhí)行的操作之前,它允許一個(gè)或多個(gè)線程一直等待。 下面通過本文給大家分享Java concurrency之CountDownLatch原理和示例,需要的的朋友參考下吧2017-06-06
Spring Cloud Stream如何實(shí)現(xiàn)服務(wù)之間的通訊
這篇文章主要介紹了Spring Cloud Stream如何實(shí)現(xiàn)服務(wù)之間的通訊,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
Java實(shí)現(xiàn)隊(duì)列的三種方法集合
這篇文章主要介紹了Java實(shí)現(xiàn)隊(duì)列的三種方法集合,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
SpringBoot2 整合Nacos組件及環(huán)境搭建和入門案例解析
這篇文章主要介紹了SpringBoot2 整合Nacos組件,環(huán)境搭建和入門案例詳解,在整合springboot2時(shí)注意版本 0.2.x.RELEASE 對應(yīng)的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 對應(yīng)的是 Spring Boot 1.x 版本,具體內(nèi)容詳情跟隨小編一起看看吧2022-03-03
Spring AOP日志框架實(shí)現(xiàn)過程圖解
這篇文章主要介紹了Spring AOP日志框架實(shí)現(xiàn)過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
SpringBoot遇到的坑@Qualifier報(bào)紅的解決
這篇文章主要介紹了SpringBoot遇到的坑@Qualifier報(bào)紅的解決,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11

