首页 > 其他分享 >SpringBoot中生成二维码的案例实战

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

时间:2024-08-22 08:57:07浏览次数:7  
标签:实战 google SpringBoot springframework zxing 二维码 org import com

❃博主首页 : 「码到三十五」 ,同名公众号 :「码到三十五」,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端点时,将直接收到一个二维码图片作为响应。
在这里插入图片描述


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

标签:实战,google,SpringBoot,springframework,zxing,二维码,org,import,com
From: https://blog.csdn.net/qq_26664043/article/details/140938626

相关文章

  • 从源码分析 SpringBoot 的 LoggingSystem → 它是如何绑定日志组件的
    开心一刻今天心情不好,想约哥们喝点我:心情不好,给你女朋友说一声,来我家,过来喝点哥们:行!我给她说一声我:你想吃啥?我点外卖哥们:你俩定吧,我已经让她过去了我:???我踏马让你过来!和她说一声哥们:哈哈哈,我踏马寻思让她过去呢前情回顾SpringBoot2.7霸王硬上弓Logback1.3→不甜但解渴......
  • Synchronized重量级锁原理和实战(五)
    在JVM中,每个对象都关联这一个监视器,这里的对象包含可Object实例和Class实例.监视器是一个同步工具,相当于一个凭证,拿到这个凭证就可以进入临界区执行操作,没有拿到凭证就只能阻塞等待.重量级锁通过监视器的方式保证了任何时间内只允许一个线程通过监视器保护的临界区代码.......
  • TypeScript深度揭秘:Map的全方位详解、作用、特点、优势及实战应用和高级应用
            在TypeScript的广阔世界里,Map对象无疑是一个强大的存在,它提供了灵活且高效的键值对存储机制。今天,我们就来一场轻松而严谨的探秘之旅,全方位解析TypeScript中Map的定义、作用、特点、优势,并通过实战代码示例,带你领略Map的无穷魅力。引言Map是TypeScript(以及Ja......
  • springboot+vue高校多媒体教室管理系统【程序+论文+开题】-计算机毕业设计
    系统程序文件列表开题报告内容研究背景随着信息技术的飞速发展和教育改革的不断深入,高校教学模式正逐步向信息化、智能化转型。多媒体教室作为现代化教学的重要载体,其管理效率与服务质量直接影响到教学活动的开展与教学效果的提升。然而,传统的高校多媒体教室管理方式多依赖......
  • springboot+vue高校多媒体教室管理系统【程序+论文+开题】-计算机毕业设计
    系统程序文件列表开题报告内容研究背景随着信息技术的飞速发展,高校教育日益依赖于多媒体教学手段来提升教学质量与效率。传统的高校教室管理模式面临着诸多挑战,如教室资源分配不均、使用效率低下、信息更新滞后等问题,严重制约了教育资源的优化配置与利用。因此,开发一套高效......
  • springboot+vue葛根庙镇乡村服务小程序【程序+论文+开题】-计算机毕业设计(1)
    系统程序文件列表开题报告内容研究背景随着数字乡村战略的深入实施,农村地区正逐步迈向信息化、智能化的发展道路。葛根庙镇,作为典型的乡村地区,其经济、社会、文化的全面发展离不开信息技术的有力支撑。然而,当前乡村服务信息散乱、获取渠道不畅、农牧技术推广效率低等问题日......
  • springboot+vue高校大学生党员活动管理平台【程序+论文+开题】-计算机毕业设计
    系统程序文件列表开题报告内容研究背景在信息化高速发展的今天,高校党建工作面临着新的机遇与挑战。随着大学生党员数量的不断增加,如何高效地组织、管理和展示党员活动,成为提升党建工作质量、增强党员凝聚力和战斗力的重要课题。传统的管理方式往往依赖于纸质材料和人工统计......
  • springboot+vue高校实习管理系统的设计与实现【程序+论文+开题】-计算机毕业设计
    系统程序文件列表开题报告内容研究背景随着高等教育的普及与深化,实习作为学生理论与实践相结合、提升职业技能的重要途径,其管理效率和质量直接关系到学生综合素质的培养与未来职业发展。然而,传统的高校实习管理模式往往依赖于纸质文档和人工操作,存在信息更新滞后、管理效率......
  • springboot+vue高校摄影网站【程序+论文+开题】-计算机毕业设计
    系统程序文件列表开题报告内容研究背景随着数字技术的飞速发展,摄影艺术已成为高校文化生活中不可或缺的一部分。高校师生对摄影的热爱不仅体现在专业课程的学习上,更渗透于日常记录、艺术创作及文化交流之中。然而,当前高校内缺乏一个集作品展示、学习交流、资讯分享于一体的......
  • 基于SpringBoot+Vue+uniapp的钢材销售管理系统的详细设计和实现(源码+lw+部署文档+讲
    文章目录前言详细视频演示具体实现截图技术栈后端框架SpringBoot前端框架Vue持久层框架MyBaitsPlus系统测试系统测试目的系统功能测试系统测试结论为什么选择我代码参考数据库参考源码获取前言......