Java生成二维码

Java二维码的生成。

文章目录

后端生成二维码

1.后台生成二维码接口,传入参数:高、宽、二维码内容,可生成相应高宽含该内容的二进制流(二维码图片),不传高宽则默认二维码的大小为200*200。

    /*
     * 生成二维码
     * */
    @RequestMapping(path = "/createQRCode",method = RequestMethod.POST)
    @ResponseBody
    public void createQRCode(@InterfaceParam(name="data") String data,
                             @InterfaceParam(name="height") Integer height ,
                             @InterfaceParam(name="width") Integer width,HttpServletResponse response) throws Exception, BaseException {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        int ht=200;
        int wt=200;
        BufferedImage image = QRCodeCloudPrintUtil.createImage(data,null==height?ht:height,null==width?wt:width);
        // 创建二进制的输出流
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(image, "jpeg", sos);
    }

2.createImage方法如下:

public static BufferedImage createImage(String content,int ht,int wt) {
        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 = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, wt, ht, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

3.使用postman调用如下:
传入高宽
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值