SpringBoot中生成二维码的案例分享

 更新时间:2024年08月22日 09:44:26   作者:码到三十五  
在Spring Boot项目中整合ZXing库来生成二维码是一个常见的需求,zxing是一个功能强大的开源Java库,专门用于二维码的生成与解析,它支持Android、iOS、Java等多个平台,本文小编将给大家分享SpringBoot中生成二维码的案例,需要的朋友可以参考下

引言

在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端点时,将直接收到一个二维码图片作为响应。

到此这篇关于SpringBoot中生成二维码的案例分享的文章就介绍到这了,更多相关SpringBoot生成二维码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java concurrency之CountDownLatch原理和示例_动力节点Java学院整理

    Java concurrency之CountDownLatch原理和示例_动力节点Java学院整理

    CountDownLatch是一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。 下面通过本文给大家分享Java concurrency之CountDownLatch原理和示例,需要的的朋友参考下吧
    2017-06-06
  • Spring Cloud Stream如何实现服务之间的通讯

    Spring Cloud Stream如何实现服务之间的通讯

    这篇文章主要介绍了Spring Cloud Stream如何实现服务之间的通讯,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • Java数组(Array)最全汇总(中篇)

    Java数组(Array)最全汇总(中篇)

    这篇文章主要介绍了Java数组(Array)最全汇总(中篇),本文章内容详细,通过案例可以更好的理解数组的相关知识,本模块分为了三部分,本次为中篇,需要的朋友可以参考下
    2023-01-01
  • SpringBoot中使用Redis作为全局锁示例过程

    SpringBoot中使用Redis作为全局锁示例过程

    这篇文章主要为大家介绍了SpringBoot中使用Redis作为全局锁示例过程,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-03-03
  • Java实现队列的三种方法集合

    Java实现队列的三种方法集合

    这篇文章主要介绍了Java实现队列的三种方法集合,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • Java实现24点小游戏

    Java实现24点小游戏

    这篇文章主要为大家详细介绍了Java实现24点小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-01-01
  • SpringBoot2 整合Nacos组件及环境搭建和入门案例解析

    SpringBoot2 整合Nacos组件及环境搭建和入门案例解析

    这篇文章主要介绍了SpringBoot2 整合Nacos组件,环境搭建和入门案例详解,在整合springboot2时注意版本 0.2.x.RELEASE 对应的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 对应的是 Spring Boot 1.x 版本,具体内容详情跟随小编一起看看吧
    2022-03-03
  • Spring AOP日志框架实现过程图解

    Spring AOP日志框架实现过程图解

    这篇文章主要介绍了Spring AOP日志框架实现过程图解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • java8 计算时间差的方法示例

    java8 计算时间差的方法示例

    这篇文章主要介绍了java8 计算时间差的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • SpringBoot遇到的坑@Qualifier报红的解决

    SpringBoot遇到的坑@Qualifier报红的解决

    这篇文章主要介绍了SpringBoot遇到的坑@Qualifier报红的解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11

最新评论