java生成二维码

java生成二维码图片方法如下:

 /**
     * 绘制二维码
     * @param contents 二维码内容
     * @return image 二维码图片
     * */
    private static BufferedImage encodeImg(String contents){
        BufferedImage image = null;
        try{
            BitMatrix matrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            int width = matrix.getWidth();
            int height = matrix.getHeight();
            for(int x = 0; x < width; x++){
                for(int y =0;y < height; y++){
                    image.setRGB(x, y, matrix.get(x, y) && y <= width ? BLACK : WHITE);
                }
            }
        }catch(Exception e){
            logger.error("生成二维码失败", e);
        }
        return image;
    }

以上是单独生成一个二维码图片。这里的参数contents是指扫描二维码后进行的操作一般指具体跳转页面的地址。
如果还需要在二维码中加入logo标志。则需要利用已经生成的无图片的二维码将logo进行生成。
在二维码中生成logo代码:

  /**
     * 二维码绘制logo
     * @param logoImg logo图片文件
     * @param qrCode 二维码文件
     * @param title 标题
     * */
    private static BufferedImage encodeImgLogo(File logoImg, BufferedImage qrCode, String title){
        BufferedImage newImage = null;
        try{
            int w = qrCode.getWidth();
            int h = qrCode.getHeight();

            //开始合并绘制图片
            newImage = new BufferedImage(WIDTH, HEIGHT + 80, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = (Graphics2D)newImage.getGraphics();
            g2.drawImage(qrCode, 0, 0, null);
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));

            BufferedImage logo = null;
            if(logoImg.exists() && logoImg.isFile()){
                //读取logo图片
                logo = ImageIO.read(logoImg);
                //设置二维码大小,太大,会覆盖二维码,此处20%
                int lw = logo.getWidth() > w * 2 /10 ? (w * 2 /10) : logo.getWidth();
                int lh = logo.getHeight() > h * 2 /10 ? (h * 2 /10) : logo.getHeight();
                //设置logo图片放置位置
                //中心
                int x = (w - lw) / 2;
                int y = (h - lh) / 2;
                g2.drawImage(logo, x, y, lw, lh, null);
            }

            //有宽500高80的黑色块,用白线覆盖
            for(int i = HEIGHT; i < HEIGHT + 80; i++){
                g2.drawLine(0, i, WIDTH, i);
            }

            //写入商户名称
            drawString(g2, title, w, h + 30);


            g2.dispose();
            qrCode.flush();
            if(null != logo) {
                logo.flush();
            }
            newImage.flush();
        }catch(Exception e){
            logger.error("二维码绘制logo失败:{}", e);
        }
        return newImage;
    }
以上就是利用java生成二维码功能
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值