springboot生成二维码

pom依赖

  <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>

utils工具

package com.abc.service;

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.Hashtable;


public class utils {
    public static void getQR(String text, int width, int height, String filePath) throws WriterException, IOException {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 1);

        //hints对象可以解决二维码内容中文乱码问题

        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height,hints);

        Path path = FileSystems.getDefault().getPath(filePath);
        System.out.println("path======="+path);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

    }
}

controller调用

    @RequestMapping("save")
    public String save(UserTable user) throws IOException, WriterException {
        String a="凯凯凯子我爱你";
        String fileName= UUID.randomUUID()+".png";
        //将二维码订单图片名称插入数据库中,便于前端回显二维码
        String totalName="D:\\Tupian\\"+fileName;
        utils.getQR(a,100,100,totalName);
        //调用工具类,依次传入二维码内容、宽、高、以及要保存在哪个路径
        user.setUserSf(fileName);
        Service.insert(user);
        return "redirect:/findAll";
    }

 

posted @ 2021-12-09 15:28  风云男子  阅读(354)  评论(0)    收藏  举报