zoukankan      html  css  js  c++  java
  • Java中使用google.zxing快捷生成二维码(附工具类源码)

    移动互联网时代,基于手机端的各种活动扫码和收付款码层出不穷;那我们如何在Java中生成自己想要的二维码呢?下面就来讲讲在Java开发中使用 google.zxing 生成二维码。


    一般情况下,Java生成二维码的方式有三种,一种是基于 google.zxing ,是google公司出的;一种是基于 jp.sourceforge.qrcode ,日本一家公司开发的;还有一种是基于 jquery.qrcode.jsjquery 插件。比较常用的是 google.zxing 的方式,这里我们就以其为例子讲解如何生成二维码。

    1、使用Maven版本控制

    这里使用 Maven 来控制版本,如果想要查看最新使用的版本,可以去 http://maven.aliyun.com/nexus/#nexus-search;quick~zxing 上面查看,示例使用的版本是3.3.0,引用如下:

    <dependency>
    	<groupId>com.google.zxing</groupId>
    	<artifactId>javase</artifactId>
    	<version>3.3.0</version>
    </dependency>
    

    2、生成/解码二维码工具类

    下面已经封装好了一个生成二维码的工具类以供参考:

    package com.yclimb.zxing;
    
    import com.alibaba.fastjson.JSONObject;
    import com.google.zxing.*;
    import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
    import com.google.zxing.client.j2se.MatrixToImageWriter;
    import com.google.zxing.common.BitMatrix;
    import com.google.zxing.common.HybridBinarizer;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * 二维码生成工具类
     *
     * @author yclimb
     * @date 2018/4/23
     */
    public class QRCodeUtil {
    
        private static Logger log = LoggerFactory.getLogger(QRCodeUtil.class);
    
        /**
         * 生成二维码
         * @param text 内容,可以是链接或者文本
         * @param path 生成的二维码位置
         */
        public static void encodeQRCode(String text, String path) {
            encodeQRCode(text, path, null, null, null);
        }
    
        /**
         * 生成二维码
         * @param text 内容,可以是链接或者文本
         * @param path 生成的二维码位置
         * @param width 宽度,默认300
         * @param height 高度,默认300
         * @param format 生成的二维码格式,默认png
         */
        public static void encodeQRCode(String text, String path, Integer width, Integer height, String format) {
            try {
    
                // 得到文件对象
                File file = new File(path);
                // 判断目标文件所在的目录是否存在
                if(!file.getParentFile().exists()) {
                    // 如果目标文件所在的目录不存在,则创建父目录
                    log.info("目标文件所在目录不存在,准备创建它!");
                    if(!file.getParentFile().mkdirs()) {
                        log.info("创建目标文件所在目录失败!");
                        return;
                    }
                }
    
                // 宽
                if (width == null) {
                    width = 300;
                }
                // 高
                if (height == null) {
                    height = 300;
                }
                // 图片格式
                if (format == null) {
                    format = "png";
                }
    
                // 设置字符集编码
                Map<EncodeHintType, Object> hints = new HashMap<>();
                hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
                // 生成二维码矩阵
                BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
                // 二维码路径
                Path outputPath = Paths.get(path);
                // 写入文件
                MatrixToImageWriter.writeToPath(bitMatrix, format, outputPath);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    
        /**
         * 对二维码图片进行解码
         * @param filePath 二维码路径
         * @return 解码后对内容
         */
        public static JSONObject decodeQRCode(String filePath) {
    
            try {
    
                // 读取图片
                BufferedImage image = ImageIO.read(new File(filePath));
    
                // 多步解析
                LuminanceSource source = new BufferedImageLuminanceSource(image);
                Binarizer binarizer = new HybridBinarizer(source);
                BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
    
                // 一步到位
                // BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)))
    
                // 设置字符集编码
                Map<DecodeHintType, String> hints = new HashMap<>();
                hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
    
                // 对图像进行解码
                Result result = new MultiFormatReader().decode(binaryBitmap, hints);
                // 解码内容
                JSONObject content = JSONObject.parseObject(result.getText());
    
                System.out.println("图片内容:  ");
                System.out.println("content: " + content.toJSONString());
                System.out.println("图片中格式:  ");
                System.out.println("encode: " + result.getBarcodeFormat());
    
                return content;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
    
            return null;
        }
    }
    
    

    3、测试方法

    public static void main(String[] args) {
    
       // 生成路径
       String filePath = "/Users/yclimb/Documents/tmp/first.png";
    
       // 生成二维码
       encodeQRCode("第一个二维码", filePath);
    
       // 解码二维码
       decodeQRCode(filePath);
    }
    

    结语

    到此本文就结束了,关注公众号查看更多推送!!!


    关注我的公众号


  • 相关阅读:
    mytest3.py-api接入平台获取数据
    对比python的进程和线程:多线程是假的
    bug-sqlite3
    安装python3 centos
    句式英语
    java组件学习15天
    areas表-省市区
    中转复制
    追踪路由的2种方法
    干掉头疼的finished with non-zero exit value 2
  • 原文地址:https://www.cnblogs.com/yclimb/p/9934091.html
Copyright © 2011-2022 走看看