二维码生成与传递


推荐后端只传输数据到,二维码由前端生成

一、生成二维码并以base64编码返回

hutool的二维码生成工具类

https://www.hutool.cn/docs/#/extra/%E4%BA%8C%E7%BB%B4%E7%A0%81%E5%B7%A5%E5%85%B7-QrCodeUtil

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.3.4</version>
</dependency>

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.3</version>
</dependency>
@GetMapping("exportQRcode")
@ApiOperation(value = "展示二维码")
public Result exportQRcode(@RequestParam Map<String, Object> params,HttpServletResponse response){
    //生成二维码
    //参数(二维码内容,宽,高)
    byte[] bytes = QrCodeUtil.generatePng("二维码内容", 300, 300);

    BASE64Encoder encoder = new BASE64Encoder();
    String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
    return new Result<>().ok("data:image/png;base64,"+png_base64);
}

可用以下网站验证base64是否正确

https://www.matools.com/image-base64

前端

<div class="us_logo">
    <img id="image">
</div>
$().ready(function(){
    $.ajax({
        url:".../share/shareImage",//你的后台合成路径
        dataType:"json",
        success:function(data){
            $("#image").attr("src",data);
        }
    })
})

二、生成二维码以流的方式返回

@RequestMapping("getQRCode")
public void getQRCode(String code , HttpServletResponse response , Map<String,Object> map){
    try {
        // 设置响应流信息
        response.setContentType("image/jpg");
        //response.setContentType("application/zip");    //如果流下载的类型是zip
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        OutputStream stream = response.getOutputStream();        //response.getWriter();

        //生成一个二维码图片,并以流的形式输出到前端
        BufferedImage image = QRCodeUtil.generate("二维码内容",300,300,"jpg",stream);

        stream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } 
}

generate方法,以及imageType取值

public static void generate(String content, int width, int height, String imageType, OutputStream out) {
    final BufferedImage image = generate(content, width, height);
    ImgUtil.write(image, imageType, out);
}


public static final String IMAGE_TYPE_GIF = "gif";// 图形交换格式
public static final String IMAGE_TYPE_JPG = "jpg";// 联合照片专家组
public static final String IMAGE_TYPE_JPEG = "jpeg";// 联合照片专家组
public static final String IMAGE_TYPE_BMP = "bmp";// 英文Bitmap(位图)的简写,它是Windows操作系统中的标准图像文件格式
public static final String IMAGE_TYPE_PNG = "png";// 可移植网络图形
public static final String IMAGE_TYPE_PSD = "psd";// Photoshop的专用格式Photoshop

直接访问该接口即可观察到二维码,或用以下方式

<img alt='二维码' src='' id='pic'>

$("#pic").attr("src","/getQRCode");

  目录