Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to generate QR Code based on SpringBoot

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how to generate QR codes based on SpringBoot. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

First, generate QR code based on Google development kit ZXing

(1) first, you need to add the dependency Jar of the toolkit to the pom.xml dependency configuration file, as shown below:

Com.google.zxing core 3.3.3 com.google.zxing javase 3.3.3

(2) then, create a QR code processing tool class QRCodeUtil, the core code of which is as follows:

/ * QR code tool * @ Author:debug (SteadyJack) * @ Link: weixin- > debug0868 qq- > 1948831260 * @ Date: 2020-11-16 22:38 * / public class QRCodeUtil {private static final Logger log= LoggerFactory.getLogger (QRCodeUtil.class); / / CODE_WIDTH: QR code width, unit pixel private static final int CODE_WIDTH = 400; / / CODE_HEIGHT: QR code height, unit pixel private static final int CODE_HEIGHT = 400 / / FRONT_COLOR: foreground color of QR code, 0x000000 indicates black private static final int FRONT_COLOR = 0x00000000; / / BACKGROUND_COLOR: background color of QR code, 0xFFFFFF indicates white / / demo is expressed in hexadecimal, and the color selection of front-end page CSS is the same. Note that the background color should be clearly contrasted, such as the common black and white private static final int BACKGROUND_COLOR = 0xFFFFFF Public static void createCodeToFile (String content, File codeImgFileSaveDir, String fileName) {try {if (StringUtils.isBlank (content) | | StringUtils.isBlank (fileName)) {return;} content = content.trim (); if (codeImgFileSaveDir==null | | codeImgFileSaveDir.isFile ()) {/ / the QR code image directory is empty, which is placed on the desktop by default. CodeImgFileSaveDir = FileSystemView.getFileSystemView (). GetHomeDirectory ();} if (! codeImgFileSaveDir.exists ()) {/ / QR code picture exists directory does not exist, start to create. CodeImgFileSaveDir.mkdirs ();} / / Core Code-generate QR code BufferedImage bufferedImage = getBufferedImage (content); File codeImgFile = new File (codeImgFileSaveDir, fileName); ImageIO.write (bufferedImage, "png", codeImgFile); log.info ("QR code picture generated successfully:" + codeImgFile.getPath ()) } catch (Exception e) {e.printStackTrace () }} / * * generate a QR code and output it to an output stream, which is usually used to output to a web page for display, to a web page and to a file on disk The difference lies in the last sentence ImageIO.write * write (RenderedImage im,String formatName,File output): write to file * write (RenderedImage im,String formatName,OutputStream output): output to output stream * @ param content: QR code content * @ param outputStream: output stream For example, HttpServletResponse's getOutputStream * / public static void createCodeToOutputStream (String content, OutputStream outputStream) {try {if (StringUtils.isBlank (content)) {return } content = content.trim (); / / Core code-generate the QR code BufferedImage bufferedImage = getBufferedImage (content); / / the difference is that this sentence is output to the output stream, and if the third parameter is File, then output to the file ImageIO.write (bufferedImage, "png", outputStream) Log.info ("QR code picture generated to output stream successfully...");} catch (Exception e) {e.printStackTrace ();}} / / Core Code-generate QR code private static BufferedImage getBufferedImage (String content) throws WriterException {/ / com.google.zxing.EncodeHintType: encoding hint type, enumerated type Map hints = new HashMap () / / EncodeHintType.CHARACTER_SET: sets the character encoding type hints.put (EncodeHintType.CHARACTER_SET, "UTF-8") / / EncodeHintType.ERROR_CORRECTION: set error correction / / ErrorCorrectionLevel: error correction level, L = ~ 7% correction, M = ~ 15% correction, Q = ~ 25% correction, H = ~ 30% correction / / is not set, the default is L grade, the level is different, the pattern is different, but the scanning result is the same hints.put (EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M) / / EncodeHintType.MARGIN: sets the margin of the QR code (in pixels). The smaller the value, the closer the QR code is around hints.put (EncodeHintType.MARGIN, 1); MultiFormatWriter multiFormatWriter = new MultiFormatWriter (); BitMatrix bitMatrix = multiFormatWriter.encode (content, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hints); BufferedImage bufferedImage = new BufferedImage (CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_BGR) For (int x = 0; x

< CODE_WIDTH; x++) { for (int y = 0; y < CODE_HEIGHT; y++) { bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR); } } return bufferedImage; }} 上述代码有点多,诸位可以在文末提供的下载地址将其下载下来,并用IDEA等开发工具将其打开,几乎每行代码debug都做了必要的注释,在这里就不赘述了! 总的来说,上面代码主要包含了两个部分,一部分是将实现如何将信息塞入二维码并将其生成图片存储至物理文件目录下;另一部分是实现如何直接将信息塞入二维码并生成图片最终以图片流的形式将其返回给前端调用端; (3)最后,我们需要新建一个QrCodeController控制器类,并在其中创建两个请求方法,用于测试Google ZXing工具包这种方式生成两种类型的二维码是否可行,其代码如下所示: @RequestMapping("qr/code")public class QrCodeController extends BaseController{ private static final String RootPath="E:\\shFiles\\QRCode"; private static final String FileFormat=".png"; private static final ThreadLocal LOCALDATEFORMAT=ThreadLocal.withInitial(() ->

New SimpleDateFormat ("yyyyMMddHHmmss")); / / generate the QR code and store it in the local directory @ PostMapping ("generate/v1") public BaseResponse generateV1 (String content) {BaseResponse response=new BaseResponse (StatusCode.Success); try {final String fileName=LOCALDATEFORMAT.get (). Format (new Date ()); QRCodeUtil.createCodeToFile (content,new File (RootPath), fileName+FileFormat) } catch (Exception e) {response=new BaseResponse (StatusCode.Fail.getCode (), e.getMessage ());} return response;} / / generate the QR code and return it to the front-end caller @ PostMapping ("generate/v2") public BaseResponse generateV2 (String content,HttpServletResponse servletResponse) {BaseResponse response=new BaseResponse (StatusCode.Success) Try {QRCodeUtil.createCodeToOutputStream (content,servletResponse.getOutputStream ());} catch (Exception e) {response=new BaseResponse (StatusCode.Fail.getCode (), e.getMessage ());} return response;}}

Finally, the project is run and the interface is tested with Postman. The first is the test of the controller's first method interface. The test results are shown below (the generated QR code image is stored in E:\\ shFiles\\ QRCode):

Finally, the second method interface of the controller is tested, and the test results are shown in the following figure:

PS: if you do not want to store the QR code image to the actual file directory, you can return it in the form of "picture stream"; otherwise, you can store the generated QR code image and return the access link to the front end of the image (this is a little troublesome, you should not only store and give the image access domain name and link); you can make a choice according to the actual business situation!

Second, generate QR codes based on open source Hutool tools

Next, debug is implemented in a different way, using the well-known and popular open source tool Hutool. For the same reason, you need to add the corresponding Jar dependency to pom.xml, as shown below:

Cn.hutool hutool-all 4.6.10 com.google.zxing core 3.3.3 com.google.zxing javase 3.3.3

Then, you need to customize a Java Config configuration file to display the configuration in the form of Bean and inject QrConfig, as shown in the following code:

Package com.example.qrcode.Config; import cn.hutool.extra.qrcode.QrConfig;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration; import java.awt.*; @ Configurationpublic class QRCode {@ Bean public QrConfig qrConfig () {QrConfig qrConfig=new QrConfig (); qrConfig.setBackColor (Color.white.getRGB ()); qrConfig.setForeColor (Color.black.getRGB ()); return qrConfig;}}

Then we set up a QRService to handle the real business logic that generates the QR code, and the core code is as follows:

Package com.example.qrcode.Service; import cn.hutool.extra.qrcode.QrCodeUtil;import cn.hutool.extra.qrcode.QrConfig;import com.example.qrcode.Config.QRCode;import org.springframework.stereotype.Service;import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.io.IOException; @ Servicepublic class QRService {@ Resource QrConfig qrconig Public void generateFile (String content, File file) {/ / generate to local file QrCodeUtil.generate (content,qrconig, file);} / output to stream public void generateStream (String content, HttpServletResponse response) throws IOException {QrCodeUtil.generate (content,qrconig, "png", response.getOutputStream ());}}

Finally, the call is made in the QRController controller class, as shown in the following code:

Package com.example.qrcode.Controller; import com.example.qrcode.Service.QRService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse;import java.io.IOException; @ RestControllerpublic class QRController {@ Autowired QRService qrService @ RequestMapping ("123") public void generateV3 (String content, HttpServletResponse servletResponse) throws IOException {qrService.generateStream (content,servletResponse);}}

Access the test through the browser:

Thank you for reading! This is the end of the article on "how to generate QR codes based on SpringBoot". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report