SpringBoot中生成二維碼的案例分享
引言
在Spring Boot項(xiàng)目中整合ZXing庫(kù)來(lái)生成二維碼是一個(gè)常見(jiàn)的需求。
zxing,全稱(chēng)"Zebra Crossing",是一個(gè)功能強(qiáng)大的開(kāi)源Java庫(kù),專(zhuān)門(mén)用于二維碼的生成與解析。它不僅能夠生成QR碼,還能解析包括QR碼在內(nèi)的多種二維碼格式。ZXing提供了多語(yǔ)言API,使得開(kāi)發(fā)者能夠輕松地將二維碼功能集成到各種應(yīng)用中。它支持Android、iOS、Java等多個(gè)平臺(tái),并且除了QR碼,還能解析其他一維碼和二維碼,如EAN、UPC、DataMatrix等。
1. 添加zxing庫(kù)的依賴(lài)
<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ù)類(lèi)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 concurrency之CountDownLatch原理和示例_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
CountDownLatch是一個(gè)同步輔助類(lèi),在完成一組正在其他線程中執(zhí)行的操作之前,它允許一個(gè)或多個(gè)線程一直等待。 下面通過(guò)本文給大家分享Java concurrency之CountDownLatch原理和示例,需要的的朋友參考下吧2017-06-06Spring Cloud Stream如何實(shí)現(xiàn)服務(wù)之間的通訊
這篇文章主要介紹了Spring Cloud Stream如何實(shí)現(xiàn)服務(wù)之間的通訊,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10SpringBoot中使用Redis作為全局鎖示例過(guò)程
這篇文章主要為大家介紹了SpringBoot中使用Redis作為全局鎖示例過(guò)程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-03-03Java實(shí)現(xiàn)隊(duì)列的三種方法集合
這篇文章主要介紹了Java實(shí)現(xiàn)隊(duì)列的三種方法集合,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09SpringBoot2 整合Nacos組件及環(huán)境搭建和入門(mén)案例解析
這篇文章主要介紹了SpringBoot2 整合Nacos組件,環(huán)境搭建和入門(mén)案例詳解,在整合springboot2時(shí)注意版本 0.2.x.RELEASE 對(duì)應(yīng)的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 對(duì)應(yīng)的是 Spring Boot 1.x 版本,具體內(nèi)容詳情跟隨小編一起看看吧2022-03-03Spring AOP日志框架實(shí)現(xiàn)過(guò)程圖解
這篇文章主要介紹了Spring AOP日志框架實(shí)現(xiàn)過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09SpringBoot遇到的坑@Qualifier報(bào)紅的解決
這篇文章主要介紹了SpringBoot遇到的坑@Qualifier報(bào)紅的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11