Springboot简单生成二维码

1.pom导入相关依赖

       
        com.google.zxing
            core
            3.3.3
        

        
            com.google.zxing
            javase
            3.3.3
        

        
            com.alibaba
            fastjson
            1.2.46
        

2.创建测试controller

package com.example.qrcode.controller;

import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Maps;
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.Map;

@Controller
public class QrController {

    @GetMapping(value = "qrcode")
    public void qrcode(HttpServletResponse response) throws Exception {
        Map hints = Maps.newHashMap();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //封装二维码参数
        JSONObject codeParams = new JSONObject();
        codeParams.put("username","凯毛");
        codeParams.put("password","123456");
        codeParams.put("sex","男");
        String content = codeParams.toJSONString();  //二维码内容
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 300, 300, hints);
        response.reset();//HttpServletResponse
        response.setContentType("image/png");
        ServletOutputStream out = response.getOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "png", out);
    }
}

3.访问测试localhost:8080/qrcode

image.png

ok

你可能感兴趣的:(Springboot简单生成二维码)