java实现生成二维码

java实现生成二维码的功能,需要用到谷歌的zxing包。所以实现功能的第一步就是在pom.xml配置文件中注入依赖,如下图。
在这里插入图片描述
依赖的代码形式就是:

<dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>

当然也可以从maven仓库下载jar包: http://central.maven.org/maven2/com/google/zxing/core/

注入依赖之后,开始实现二维码生成的功能:生成二维码,储存关键字“扫描二维码”并且把二维码以字节流的形式返回。

Controllar层设置http信息并且返回字节流:

 /**
     * 用户请求二维码
     *
     * @return
     */
    @PostMapping(value = "/qrcode/plat")
    @ResponseBody
    public ResponseEntity<byte[]> getQRcode(@RequestBody LoginInformation loginInfo) throws IOException, WriterException {
        HttpStatus httpStatus = HttpStatus.OK;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        BitMatrix qrcode = loginServiceImpl.getQrcode(loginInfo);
        if (qrcode != null) {
            BufferedImage image = toBufferedImage(qrcode);
            ImageIO.write(image, "png", out);
        }

        return new ResponseEntity<byte[]>(out.toByteArray(), headers, httpStatus);
    }

service层设置二维码的具体信息并且生成二维码:

   public BitMatrix getQrcode(LoginInformation loginInfo) throws WriterException, IOException {
        int width = 300;
        int height = 300;
        String format = "png";
        String contents = "扫描二维码";
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 1);//设置二维码边的空度,非负数
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
        return bitMatrix;
    }

代码完成之后,使用postman调用接口,可得生成的二维码。
在这里插入图片描述

扫描二维码可得:
在这里插入图片描述

如果想要是实现扫描二维码之后跳转到一个网页,那么就可以把contents关键字存储的信息换成网页地址。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值