利用Spring Boot+zxing,生成二维码还能这么简单

2022-10-16,,,,

在网站开发中,经常会遇到要生成二维码的情况,比如要使用微信支付、网页登录等,本文分享一个spring boot生成二维码的例子,这里用到了google的zxing工具类。

本文目录

一、二维码简介

二维码又称为qr code,qr全称是quick response,是一个近几年来移动设备上超流行的一种编码方式。

二维码是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的。

主要应用场景如下:

  • 信息获取(名片、地图、wifi密码、资料)
  • 网站跳转(跳转到微博、手机网站、网站)
  • 广告推送(用户扫码,直接浏览商家推送的视频、音频广告)
  • 手机电商(用户扫码、手机直接购物下单)
  • 防伪溯源(用户扫码、即可查看生产地;同时后台可以获取最终消费地)
  • 优惠促销(用户扫码,下载电子优惠券,抽奖)
  • 会员管理(用户手机上获取电子会员信息、vip服务)
  • 手机支付(扫描商品二维码,通过银行或第三方支付提供的手机端通道完成支付)
  • 账号登录(扫描二维码进行各个网站或软件的登录)

二、编写代码生成二维码

1.引入jar包

pom.xml中引入zxing的jar包。

<!-- 二维码支持包 -->
<dependency>
    <groupid>com.google.zxing</groupid>
    <artifactid>core</artifactid>
    <version>3.2.0</version>
</dependency>
<dependency>
    <groupid>com.google.zxing</groupid>
    <artifactid>javase</artifactid>
    <version>3.2.0</version>
</dependency>

2.编写工具类

qrcodeutil.java代码如下:

/**
 * qrcodeutil 生成二维码工具类
 */
public class qrcodeutil {

    private static final string charset = "utf-8";
    private static final string format_name = "jpg";
    // 二维码尺寸
    private static final int qrcode_size = 300;
    // logo宽度
    private static final int width = 60;
    // logo高度
    private static final int height = 60;

    private static bufferedimage createimage(string content, string imgpath, boolean needcompress) throws exception {
        hashtable hints = new hashtable();
        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++) {
                image.setrgb(x, y, bitmatrix.get(x, y) ? 0xff000000 : 0xffffffff);
            }
        }
        if (imgpath == null || "".equals(imgpath)) {
            return image;
        }
        // 插入图片
        qrcodeutil.insertimage(image, imgpath, needcompress);
        return image;
    }

    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);
        if (needcompress) { // 压缩logo
            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 g = tag.getgraphics();
            g.drawimage(image, 0, 0, null); // 绘制缩小后的图
            g.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();
    }

    public static void encode(string content, string imgpath, string destpath, boolean needcompress) throws exception {
        bufferedimage image = qrcodeutil.createimage(content, imgpath, needcompress);
        mkdirs(destpath);
        imageio.write(image, format_name, new file(destpath));
    }

    public static bufferedimage encode(string content, string imgpath, boolean needcompress) throws exception {
        bufferedimage image = qrcodeutil.createimage(content, imgpath, needcompress);
        return image;
    }

    public static void mkdirs(string destpath) {
        file file = new file(destpath);
        // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isdirectory()) {
            file.mkdirs();
        }
    }

    public static void encode(string content, string imgpath, outputstream output, boolean needcompress)
            throws exception {
        bufferedimage image = qrcodeutil.createimage(content, imgpath, needcompress);
        imageio.write(image, format_name, output);
    }

    public static void encode(string content, outputstream output) throws exception {
        qrcodeutil.encode(content, null, output, false);
    }
}

3.编写控制层代码

qrcodecontroller.java代码如下:

    /**
     * 根据 url 生成 普通二维码
     */
    @requestmapping(value = "/createcommonqrcode")
    public void createcommonqrcode(httpservletresponse response, string url) throws exception {
        servletoutputstream stream = null;
        try {
            stream = response.getoutputstream();
            //使用工具类生成二维码
            qrcodeutil.encode(url, stream);
        } catch (exception e) {
            e.getstacktrace();
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }

    /**
     * 根据 url 生成 带有logo二维码
     */
    @requestmapping(value = "/createlogoqrcode")
    public void createlogoqrcode(httpservletresponse response, string url) throws exception {
        servletoutputstream stream = null;
        try {
            stream = response.getoutputstream();
            string logopath = thread.currentthread().getcontextclassloader().getresource("").getpath() 
                    + "templates" + file.separator + "logo.jpg";
            //使用工具类生成二维码
            qrcodeutil.encode(url, logopath, stream, true);
        } catch (exception e) {
            e.getstacktrace();
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }
    }

4.运行并查看效果

本项目中提供了生成普通二维码和带有logo二维码的两个接口,启动项目,我们来演示下生成下http://www.baidu.com这个url的二维码;

  1. 生成普通二维码
    本地浏览器打开http://localhost:8080/createcommonqrcode?url=http://www.baidu.com,生成的二维码截图如下:

生成百度的普通二维码

  1. 生成带logo的二维码
    本地浏览器打开http://localhost:8080/createlogoqrcode?url=http://www.baidu.com,生成的二维码截图如下:

生成百度的带logo二维码

到此spring boot 2.x中利用zxing生成二维码功能全部实现,有问题欢迎留言沟通哦!
完整源码地址: https://github.com/suisui2019/springboot-study

推荐阅读

1.从技术的角度分析下为什么不要在网上发“原图”
2.spring boot 2.x 如何快速整合jpa?
3.spring boot之profile--快速搞定多环境使用与切换
4.spring boot 2.x整合spring-cache,让你的网站速度飞起来
5.利用spring boot+wxjava实现网站集成微信登录功能


限时领取免费java相关资料,涵盖了java、redis、mongodb、mysql、zookeeper、spring cloud、dubbo/kafka、hadoop、hbase、flink等高并发分布式、大数据、机器学习等技术。
关注下方公众号即可免费领取:

 

《利用Spring Boot+zxing,生成二维码还能这么简单.doc》

下载本文的Word格式文档,以方便收藏与打印。