二维码生成

未匹配的标注

在 Spring Boot 中集成 ZXing 生成和解析二维码非常便捷。以下是完整步骤:


1. 添加依赖
pom.xml 中引入 ZXing 核心库和 JavaSE 扩展(注意版本号可用最新稳定版):

<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. 工具类封装
创建二维码工具类 QRCodeUtils.java

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

@Component
public class QRCodeUtils {

    // 生成二维码字节流(可直接返回给前端)
    public byte[] generateQRCode(String content, int width, int height) throws Exception {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 容错级别
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 中文支持

        QRCodeWriter writer = new QRCodeWriter();
        BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            MatrixToImageWriter.writeToStream(matrix, "PNG", out);
            return out.toByteArray();
        }
    }
}

3. 创建REST接口
编写Controller类 QRCodeController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class QRCodeController {

    @Autowired
    private QRCodeUtils qrCodeUtils;

    // 生成二维码接口
    @GetMapping(value = "/qrcode", produces = MediaType.IMAGE_PNG_VALUE)
    public byte[] generateQRCode(@RequestParam String content,
                                 @RequestParam(defaultValue = "300") int width,
                                 @RequestParam(defaultValue = "300") int height) throws Exception {
        return qrCodeUtils.generateQRCode(content, width, height);
    }
}

4. 测试二维码生成
启动应用后,通过浏览器访问:

http://localhost:8080/qrcode?content=https://example.com&width=200&height=200

即可看到生成的二维码图片。


5. 解析二维码(可选扩展)
增加解析工具方法(需先上传图片到服务端):

// 在 QRCodeUtils 中添加
public String decodeQRCode(byte[] qrCodeBytes) throws Exception {
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(qrCodeBytes));
    LuminanceSource source = new BufferedImageLuminanceSource(image);
    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

    Result result = new MultiFormatReader().decode(bitmap);
    return result.getText();
}

6. 配置文件(可选)
application.properties 中添加静态资源路径(若需要保存二维码到本地):

# 允许访问生成的二维码文件
spring.resources.static-locations=classpath:/static/,file:./qrcodes/

常见问题

  1. 依赖冲突:确保 javase 依赖存在,否则无法生成图片。
  2. 中文乱码:必须设置 EncodeHintType.CHARACTER_SETUTF-8
  3. 图片格式:默认支持 PNG,如需 JPG 需调整 MatrixToImageWriter.writeToStream 参数。

总结
通过以上步骤,你的 Spring Boot 应用已具备生成和解析二维码的能力。可直接通过接口生成动态二维码,或扩展文件上传功能实现解析。

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
唐章明
讨论数量: 0
发起讨论 查看所有版本


暂无话题~