前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java生成二维码,微信直接扫描出结果

java生成二维码,微信直接扫描出结果

作者头像
公众号 IT老哥
发布2020-12-15 14:33:27
1.9K0
发布2020-12-15 14:33:27
举报

前言

二维码在我们的生活中随处可见,作为程序员的我们,有没有想过自己生成一个二维码玩玩呢,其实很简单,我们直接用谷歌提供的com.google.zxing就可以了。

二维码效果图

PC端生成二维码

生成的二维码分为两部分

  • 黑白相间的二维码
  • 中间B站的LOGO图标

我们下面的代码会讲到如何实现这两个图片的融合。

微信扫一扫

不光可以扫描出文字,还可以扫描跳转链接,还可以扫描生成图片。只要在输入框里填入不同的信息就可以了。

比如我们输入https://www.baidu.com/,扫描二维码后就可以直接跳到百度网站

比如我们输入图片地址https://img-blog.csdnimg.cn/20200629104712300.jpg,扫描后就会显示相应的图片。

代码实现

maven配置

<!-- 添加 google 提供的二维码依赖 -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.0</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.0</version>
</dependency>
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>

controller

@RestController
@RequestMapping("/qrCode")
public class QRCodeGeneratorController {

   @GetMapping("/generator")
   public void encodeQrCode(String codeContent, HttpServletResponse response) {
      // 嵌入二维码的图片路径
      String imgPath = "C:\\Users\\hp\\Desktop\\bilibili.jpg";
      try {
         QRCodeUtil.encode(codeContent, imgPath, true, response.getOutputStream());
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

核心util类

public class QRCodeUtil {
    
    private static final String CHARSET = "utf-8";

    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;

    // LOGO宽度
    private static final int WIDTH = 100;

    // LOGO高度
    private static final int HEIGHT = 100;

    /**
     * 将前端传入的信息,编码成二维码
     * @param content
     * @param imgPath
     * @param needCompress
     * @param outputStream
     * @throws Exception
     */
    public static void encode(String content, String imgPath, boolean needCompress, OutputStream outputStream) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        ImageIO.write(image, "png", outputStream);
    }

    /**
     * 生成二维码核心代码
     * @param content
     * @param imgPath
     * @param needCompress
     * @return
     * @throws Exception
     */
    private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {

        HashMap hints = new HashMap(16);
        // 指定要使用的纠错程度,例如在二维码中。
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 指定字符编码
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        // 指定生成条形码时要使用的边距(以像素为单位)。
        hints.put(EncodeHintType.MARGIN, 1);

        // 生成一个二维位矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                hints);

        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++) {
                // true就是黑色,false就是白色
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入LOGO图片
        QRCodeUtil.insertImage(image, imgPath, needCompress);
        return image;
    }

    /**
     * 插入bilibili的LOGO图片
     * @param source
     * @param imgPath
     * @param needCompress
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);

        // 压缩LOGO
        if (needCompress) {
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }

            // 创建此图像的缩放版本。
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics graphics = tag.getGraphics();

            // 绘制缩小后的图
            graphics.drawImage(image, 0, 0, null);
            graphics.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 解码,将二维码里的信息解码出来
     * @param path
     * @return
     * @throws Exception
     */
    public static String decode(String path) throws Exception {
        File file = new File(path);
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

}

html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
    <title>二维码生成器</title>
    <style type="text/css">
        textarea {
            font-size: 16px;
            width: 300px;
            height: 100px;
        }

        .hint {
            color: red;
            display: none;
        }

        .qrCodeDiv {
            width: 200px;
            height: 200px;
            border: 2px solid sandybrown;
        }

        .qrCodeDiv img {
            max-height: 100%;
            max-width: 100%;
        }
    </style>
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>

    <script type="text/javascript">
        $(function () {
            $("button").click(function () {
                var codeContent = $("textarea").val();
                console.log(codeContent);
                /**
                 * 如果输出的内容为空,则提示,否则改变 img 的地址重新生成 二维码
                 */
                if (codeContent.trim() == "") {
                    $(".hint").text("二维码内容不能为空").fadeIn(500);
                } else {
                    $(".hint").text("").fadeOut(500);
                    /**coco 是应用名称,qrCode 是后台访问路径,codeContent 是后台控制层接收的参数*/
                    $("#codeImg").attr("src", "/qrCode/generator?codeContent=" + codeContent);
                }
            });
        });
    </script>
</head>
<body>

<textarea placeholder="二维码内容..."></textarea><br>
<button>生成二维码</button>
<span class="hint"></span>

<!--二维码显示曲,与验证码一样,直接使用 img 标签请求即可-->
<!--下面是 thymeleaf 的写法,qrCode 是后台访问的路径, codeContent 是 get 请求携带的参数,值为 "谢谢"-->
<!--如果是纯 html 或者 jsp 写法,则可以用:<img src="/coco/qrCode?codeContent=谢谢" id="codeImg">,coco 是应用名称-->
<div class="qrCodeDiv">
    <img src="" th:src="@{/qrCode(codeContent=谢谢)}" id="codeImg">
</div>
</body>
</html>

代码下载地址

链接:https://pan.baidu.com/s/1Qt1ttXGjagRn3aKWXZ8Cog

提取码:dukf

大家别忘了替换controller里的LOGO图片地址

// 嵌入二维码的图片路径
String imgPath = "C:\\Users\\hp\\Desktop\\bilibili.jpg";
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-11-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 IT老哥 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 二维码效果图
    • PC端生成二维码
      • 微信扫一扫
      • 代码实现
        • maven配置
          • controller
            • 核心util类
              • html
              • 代码下载地址
              相关产品与服务
              验证码
              腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档