SpringBoot中生成二維碼的案例分享
引言
在Spring Boot項(xiàng)目中整合ZXing庫(kù)來(lái)生成二維碼是一個(gè)常見的需求。
zxing,全稱"Zebra Crossing",是一個(gè)功能強(qiáng)大的開源Java庫(kù),專門用于二維碼的生成與解析。它不僅能夠生成QR碼,還能解析包括QR碼在內(nèi)的多種二維碼格式。ZXing提供了多語(yǔ)言API,使得開發(fā)者能夠輕松地將二維碼功能集成到各種應(yīng)用中。它支持Android、iOS、Java等多個(gè)平臺(tái),并且除了QR碼,還能解析其他一維碼和二維碼,如EAN、UPC、DataMatrix等。
1. 添加zxing庫(kù)的依賴
<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)訪問(wèn)/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來(lái)返回二維碼圖片:
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 注冊(cè)BufferedImage消息轉(zhuǎn)換器返回圖片
3.2中返回圖片也可以通過(guò)注冊(cè)一個(gè)SpringBoot的消息轉(zhuǎn)換器來(lái)實(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)訪問(wèn)/qr端點(diǎn)時(shí),將直接收到一個(gè)二維碼圖片作為響應(yīng)。

到此這篇關(guān)于SpringBoot中生成二維碼的案例分享的文章就介紹到這了,更多相關(guān)SpringBoot生成二維碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java使用POI實(shí)現(xiàn)Excel文件的創(chuàng)建與處理
這篇文章主要為大家詳細(xì)介紹了Java如何采用POI原生方式實(shí)現(xiàn)自定義Excel表格表頭并生成Excel文件,文中的示例代碼講解詳細(xì),有需要的小伙伴可以了解下2025-05-05
教你如何編寫簡(jiǎn)單的網(wǎng)絡(luò)爬蟲
實(shí)際的爬蟲是從一系列的種子鏈接開始。種子鏈接是起始節(jié)點(diǎn),種子頁(yè)面的超鏈接指向的頁(yè)面是子節(jié)點(diǎn)(中間節(jié)點(diǎn)),對(duì)于非html文檔,如excel等,不能從中提取超鏈接,看做圖的終端節(jié)點(diǎn)2013-10-10
SpringBoot集成Spring security JWT實(shí)現(xiàn)接口權(quán)限認(rèn)證
這篇文章主要介紹了SpringBoot集成Spring security JWT實(shí)現(xiàn)接口權(quán)限認(rèn)證,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Java 中Timer和TimerTask 定時(shí)器和定時(shí)任務(wù)使用的例子
這篇文章主要介紹了Java 中Timer和TimerTask 定時(shí)器和定時(shí)任務(wù)使用的例子,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-05-05
Mybatis如何自動(dòng)生成數(shù)據(jù)庫(kù)表結(jié)構(gòu)總結(jié)
這篇文章主要給大家介紹了關(guān)于Mybatis如何自動(dòng)生成數(shù)據(jù)庫(kù)表結(jié)構(gòu)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用Mybatis具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
SpringMVC框架整合Junit進(jìn)行單元測(cè)試(案例詳解)
本文詳細(xì)介紹在SpringMVC任何使用Junit框架。首先介紹了如何引入依賴,接著介紹了編寫一個(gè)測(cè)試基類,并且對(duì)其中涉及的各個(gè)注解做了一個(gè)詳細(xì)說(shuō)明,感興趣的朋友跟隨小編一起看看吧2021-05-05
Spring Boot定制type Formatters實(shí)例詳解
在本篇文章里小編給大家整理的是關(guān)于Spring Boot定制type Formatters實(shí)例知識(shí)點(diǎn),需要的朋友們學(xué)習(xí)下。2019-11-11
通過(guò)使用Byte?Buddy便捷創(chuàng)建Java?Agent
這篇文章主要為大家介紹了如何通過(guò)使用Byte?Buddy便捷創(chuàng)建Java?Agent的使用說(shuō)明,有需要的朋友可以借鑒參考下希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03

