移动互联网时代,基于手机端的各种活动扫码和收付款码层出不穷;那我们如何在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);
}

结语

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



Java中使用google.zxing快捷生成二维码(附工具类源码)的更多相关文章

  1. Java中Date类型如何向前向后滚动时间,( 附工具类)

    Java中的Date类型向前向后滚动时间(附工具类) 废话不多说,先看工具类: import java.text.SimpleDateFormat; import java.util.Calendar ...

  2. com.google.zxing:core 生成二维码的简单使用

    String content = ""; int size = 240; Hashtable<EncodeHintType, String> hints = new H ...

  3. java二维码生成-谷歌(Google.zxing)开源二维码生成学习及实例

    java二维码生成-谷歌(Google.zxing)开源二维码生成的实例及介绍   我们使用比特矩阵(位矩阵)的QR码编码在缓冲图片上画出二维码 实例有以下一个传入参数 OutputStream ou ...

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

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

  5. 基于Asp.Net Core,利用ZXing来生成二维码的一般流程

    本文主要介绍如何在.net环境下,基于Asp.Net Core,利用ZXing来生成二维码的一般操作.对二维码工作原理了解,详情见:https://blog.csdn.net/weixin_36191 ...

  6. C# ZXing.Net生成二维码、识别二维码、生成带Logo的二维码(二)

    1.使用ZXint.Net生成带logo的二维码 /// <summary> /// 生成带Logo的二维码 /// </summary> /// <param name ...

  7. 使用python调用zxing库生成二维码图片

    (1)     安装Jpype 用python调用jar包须要安装jpype扩展,在Ubuntu上能够直接使用apt-get安装jpype扩展 $ sudo apt-get install pytho ...

  8. C#MVC用ZXing.Net生成二维码/条形码

    开篇:zxing.net是.net平台下编解条形码和二维码的工具. 首先创建新项目 选择MVC模板  添加一个控制器  在项目引用中的引用ZXing 进行联网下载 控制器需要引用 后台控制器   pu ...

  9. Google API在线生成二维码的方法

    1.先看一个实例,是用Google API生成西部e网的网站地址www.weste.net二维码的方法: http://chart.apis.google.com/chart?cht=qr&c ...

随机推荐

  1. 执行composer install后报错:执行composer install后报错: d11wtq/boris v1.0.10 requires ext-pcntl * -> the requested PHP extension pcntl is missing from your system.

    执行composer install后报错: d11wtq/boris v1.0.10 requires ext-pcntl * -> the requested PHP extension p ...

  2. 又一家药企IPO被拒,原因竟然是……

    版权所有,未经授权不得转载,QQ:231469242 导读 近日,中国证监会官网发布公告,河南润弘制药首发未IPO能通过,成为今年第4家IPO被否的制药企业.中国证监会拒绝润弘制药的原因是润弘制药产品 ...

  3. canvas 入门

    <canvas>是HTML5新增的,是可以使用脚本(JavaScript)在其中绘制图像的HTML元素. canvas是由HTML代码配合高度和宽度属性而定义出的可绘制区域,JavaScr ...

  4. H5页面中唤起native app

    现在各类app,分享出去的H5页面中,一般都会带着一个立即打开的按钮,如果本地安装了app,那么就直接唤起本地的app,如果没有安装,则跳转到下载.这是一个很正常的推广和导流量的策略,最近产品经理就提 ...

  5. zookeeper系列之:独立模式部署zookeeper服务

    一.简述 独立模式是部署zookeeper服务的三种模式中最简单和最基础的模式,只需一台机器即可,独立模式仅适用于学习,开发和生产都不建议使用独立模式.本文介绍以独立模式部署zookeeper服务器的 ...

  6. Seven Techniques for Data Dimensionality Reduction

    Seven Techniques for Data Dimensionality Reduction Seven Techniques for Data Dimensionality Reductio ...

  7. 内核:为了fan的健康,我的重新编译记录

    email: jiqingwu@gmail.com date: 2008-02-13 关键词:ubuntu cpu cpufreqd cpufrequtils 编译 内核 装上ubuntu7.10后, ...

  8. 在windows的IDEA运行Presto

    After building Presto for the first time, you can load the project into your IDE and run the server. ...

  9. 配置多个ssh-key

    搞了三天没搞出来,还在男朋友面前哭了一场,真心觉得我只该吃屎,我好没用.哎.. 首先在上一篇记录了如何生成ssh-key,并使本地可以通过ssh的方式克隆和推送项目.但如果你有个github账号,有个 ...

  10. [转]std::set、自定义类型与比较函数

    转自:http://www.189works.com/article-42025-1.html 怎样在set中放入自定义类型?这个问题通过谷歌就可以得到不少答案:1.定义一个函数对象并在定义set的时 ...