Springboot生成二维码并回显到页面上

一、导入依赖

<dependency>
            <groupId>com.google.zxinggroupId>
            <artifactId>javaseartifactId>
            <version>3.2.1version>
dependency>

测试

不带logo的二维码

package com.tubai;

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.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class TestController {
    @GetMapping("/QrTest")
    public void get(HttpServletResponse response) throws Exception {
        int width = 200;
        int height = 200;
        String format = "png";
        String content = "jwttttt";
        ServletOutputStream out = response.getOutputStream();
        Map<EncodeHintType,Object> config = new HashMap<>();
        config.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        config.put(EncodeHintType.MARGIN, 0);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,height,config);
        MatrixToImageWriter.writeToStream(bitMatrix,format,out);
        System.out.println("二维码生成完毕,已经输出到页面中。");
    }
}

然后直接访问就可以了
Springboot生成二维码并回显到页面上_第1张图片
或者用html的img标签自由的决定怎么放


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<img src="/QrTest">
body>
html>

Springboot生成二维码并回显到页面上_第2张图片

你可能感兴趣的:(Springboot生成二维码并回显到页面上)