0
点赞
收藏
分享

微信扫一扫

python入门(一)配置环境和选择IDE

SpringBoot使用Zxing生成二维码

什么是Zxing

ZXing,一个支持在图像中解码和生成条形码(如二维码、PDF 417、EAN、UPC、Aztec、Data Matrix、Codabar)的库。ZXing(“zebra crossing”)是一个开源的、多格式的、用Java实现的一维/二维条码图像处理库,具有到其他语言的端口。

具体实现

对于在Spring项目中使用Zxing生成二维码,其实比较简单,只需要引入依赖,然后调用方法,并传入需要的参数即可。
最核心的代码就是
QRCodeWriter qrCodeWriter=new QRCodeWriter(); bitMatrix=qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
text :二维码中携带的内容
BarcodeFormat.QR_CODE :是一个枚举值,表示二维码(Quick Response Code)格式
width: 宽
height: 高
hints: 是一个map,包含一些其他的设置内容

1. 在pom文件中导入依赖

		<!-- ZXing二维码 -->
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>3.4.1</version> 
		</dependency>
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.4.1</version>
		</dependency>

2. 二维码生成工具类

生成的二维码可以输出到本地文件中,也可以直接以IO流的形式返回给前端,前端再进行二维码的显示。

package com.lixy.sharingcurriculum.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
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 java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;

public class QRCodeGenerator {

    /**
     * 生成二维码输出文件
     * @param text
     * @throws WriterException
     * @throws IOException
     */
    public static void generateQRCodeImage(String text) throws WriterException, IOException {

        int width = 350;
        int height = 350;
        String filePath = "C:/Users/li/Pictures/qrtest.png";

        // 定义二维码的参数
        HashMap<EncodeHintType, ErrorCorrectionLevel> hintMap = new HashMap<>();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
    }

    /**
     * 生成二维码并以IO流返回
     * @param text
     * @return
     * @throws WriterException
     */
    public static BitMatrix createQRCode(String text) throws IOException {

        int width=200;
        int height=200;

        HashMap<EncodeHintType,Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET,"UTF-8"); //指定字符编码为“utf-8”
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); //指定二维码的纠错等级为中级
        hints.put(EncodeHintType.MARGIN, 2); //设置图片的边距,单位像素,非负值

        BitMatrix bitMatrix=null;

        try{
            QRCodeWriter qrCodeWriter=new QRCodeWriter();
            bitMatrix=qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        }catch (WriterException e){
            e.printStackTrace();
        }

        return bitMatrix;
    }

    public static void main(String[] args) {
        try {
            generateQRCodeImage("code");
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 控制层和服务层

/**
     * 生成带有课程表信息的二维码
     */
    @PostMapping("/generateQRCode")
    public void generateQRCode(String scheduleid,HttpServletResponse response) throws IOException {
        //设置响应流信息
        response.setContentType("image/png");
        //没有缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        //设置过期的时间戳,为0表示立即过期
        response.setDateHeader("Expire", 0);

        BitMatrix bitMatrix=scheduleService.generateQRCode(scheduleid);

        OutputStream stream=response.getOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix,"png",stream);

    }
/**
     * 生成带有课程表信息的二维码
     * @return
     */
    @Override
    public BitMatrix generateQRCode(String scheduleid) throws IOException {

        Schedule schedule=scheduleMapper.selectById(scheduleid);

        //将课表信息转换为json格式
        String scheduleJson= JSON.toJSONString(schedule);
        return QRCodeGenerator.createQRCode(scheduleJson);

    }

4. 前端

wx.request({
      url: 'http://localhost:8080/schedule/generateQRCode?scheduleid='+this.data.id,
      method:'POST',
      responseType: 'arraybuffer', // 指定返回类型为ArrayBuffer
      success:res=>{
        const base64=wx.arrayBufferToBase64(res.data);
        const imagesrc='data:image/png;base64,'+base64;
        console.log("二维码url:"+imagesrc)
        this.setData({
          qrCodeImg:imagesrc
        })
      }
    })

		<view>
			扫描二维码即可导入课表
		</view>
		<image src="{{qrCodeImg}}" mode="aspectFit"/>  

总结

另外还可以使用一些其他的方式生成二维码,比如基于开源的Hutool工具生成二维码,可以参考SpringBoot系列(22):Java生成二维码的几种实现方式(基于Spring Boot)
也可以直接使用js生成,有QRCode.js库可以直接引用。

参考

使用Zxing生成二维码
Java生成二维码并以IO流的形式返回给前端展示(不需写入服务器),以及下载二维码图片

举报

相关推荐

0 条评论