SpringBoot中生成二维码的案例实战

❃博主首页 : 「码到三十五」 ,同名公众号 :「码到三十五」,wx号 : 「liwu0213」
☠博主专栏 : <mysql高手> <elasticsearch高手> <源码解读> <java核心> <面试攻关>
♝博主的话 : 搬的每块砖,皆为峰峦之基;公众号搜索「码到三十五」关注这个爱发技术干货的coder,一起筑基

在Spring Boot项目中整合ZXing库来生成二维码是一个常见的需求。

zxing,全称"Zebra Crossing",是一个功能强大的开源Java库,专门用于二维码的生成与解析。它不仅能够生成QR码,还能解析包括QR码在内的多种二维码格式。ZXing提供了多语言API,使得开发者能够轻松地将二维码功能集成到各种应用中。它支持Android、iOS、Java等多个平台,并且除了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. 生成二维码

创建一个SpringBoot服务类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. 调用二维码服务
3.1 将二维码图拍你保存

最后在SpringBoot的Controller中调用这个服务:

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();
        }
    }
}

当访问/generateQRCode端点并传递textwidthheight参数时,它将生成一个名为myqrcode.png的二维码图片并保存到项目根目录下。

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,然后转换为BufferedImage,以便获取二维码图片的字节流。

3.2 注册BufferedImage消息转换器返回图片

3.2中返回图片也可以通过注册一个SpringBoot的消息转换器来实现:

@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);
 }

}

现在,当访问/qr端点时,将直接收到一个二维码图片作为响应。
在这里插入图片描述


关注公众号[码到三十五]获取更多技术干货 !

  • 24
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
可以使用Google开源的Zxing库来生成二维码,以下是基于Spring Boot的批量生成二维码的示例代码: 1. 引入依赖 在pom.xml添加以下依赖: ```xml <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.3</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.3</version> </dependency> ``` 2. 编写生成二维码的工具类 ```java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; 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; public class QrCodeUtils { private static final int WIDTH = 300; // 二维码宽度 private static final int HEIGHT = 300; // 二维码高度 private static final String FORMAT = "png"; // 二维码格式 private static final String CHARSET = "UTF-8"; // 字符集 private static final int MARGIN = 1; // 边距 /** * 生成二维码 * * @param content 二维码内容 * @param file 二维码文件 * @throws Exception */ public static void generateQRCode(String content, File file) throws Exception { BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, getDecodeHintType()); BufferedImage image = toBufferedImage(bitMatrix); ImageIO.write(image, FORMAT, file); } /** * 批量生成二维码 * * @param contents 二维码内容列表 * @param dir 二维码目录 * @throws Exception */ public static void batchGenerateQRCode(List<String> contents, File dir) throws Exception { if (!dir.exists()) { dir.mkdirs(); } for (int i = 0; i < contents.size(); i++) { String content = contents.get(i); String fileName = "qrcode_" + (i + 1) + "." + FORMAT; File file = new File(dir, fileName); generateQRCode(content, file); } } /** * 获取编码提示类型 * * @return */ private static EncodeHintType getDecodeHintType() { EncodeHintType encodeHintType = EncodeHintType.ERROR_CORRECTION; ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.H; return encodeHintType; } /** * BitMatrix转BufferedImage * * @param matrix * @return */ private static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } return image; } } ``` 3. 调用工具类批量生成二维码 ```java import java.io.File; import java.util.ArrayList; import java.util.List; public class QrCodeTest { public static void main(String[] args) throws Exception { List<String> contents = new ArrayList<>(); contents.add("http://www.baidu.com"); contents.add("http://www.google.com"); contents.add("http://www.github.com"); File dir = new File("D:/qrcode"); QrCodeUtils.batchGenerateQRCode(contents, dir); } } ``` 以上代码会在D:/qrcode目录下生成三个二维码文件,内容分别为http://www.baidu.com、http://www.google.com、http://www.github.com。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码到三十五

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值