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

前言

二维码在我们的生活中随处可见,作为程序员的我们,有没有想过自己生成一个二维码玩玩呢,其实很简单,我们直接用谷歌提供的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";

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值