热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Zxing生成二维码工具类

1.代码importcom.google.zxing.BarcodeFormat;importcom.google.zxing.BinaryBitmap;importcom.

1. 代码

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;/*** @describe: 二维码工具类* @author:houkai* @Date: 2018/4/28 16:28* @version 1.0*/
public class QRCodeUtil {private static final String CHARSET = "utf-8";private static final String FORMAT = "JPG";// 二维码尺寸private static final int QRCODE_SIZE = 300;// LOGO宽度private static final int LOGO_WIDTH = 60;// LOGO高度private static final int LOGO_HEIGHT = 60;private static BufferedImage createImage(String content, String logoPath, 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 for (int y = 0; y 0xFF000000 : 0xFFFFFFFF);}}if (logoPath == null || "".equals(logoPath)) {return image;}// 插入图片QRCodeUtil.insertImage(image, logoPath, needCompress);return image;}/*** 插入LOGO* @param source 二维码图片* @param logoPath LOGO图片地址* @param needCompress 是否压缩* @throws Exception*/private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {File file = new File(logoPath);if (!file.exists()) {throw new Exception("logo file not found.");}Image src = ImageIO.read(new File(logoPath));int width = src.getWidth(null);int height = src.getHeight(null);if (needCompress) { // 压缩LOGOif (width > LOGO_WIDTH) {width = LOGO_WIDTH;}if (height > LOGO_HEIGHT) {height = LOGO_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;}// 插入LOGOGraphics2D 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();}/*** 生成二维码(内嵌LOGO)* 二维码文件名随机,文件名可能会有重复** @param content 内容* @param logoPath LOGO地址* @param destPath 存放目录* @param needCompress 是否压缩LOGO* @throws Exception*/public static String encode(String content, String logoPath, String destPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);mkdirs(destPath);String fileName = new Random().nextInt(99999999) + "." + FORMAT.toLowerCase();ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));return fileName;}/*** 生成二维码(内嵌LOGO)* 调用者指定二维码文件名** @param content 内容* @param logoPath LOGO地址* @param destPath 生成的二维码存放目录* @param fileName 二维码文件名* @param needCompress 是否压缩LOGO* @throws Exception*/public static String encode(String content, String logoPath, String destPath, String fileName, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);mkdirs(destPath);fileName = fileName.substring(0, fileName.indexOf(".")>0 ? fileName.indexOf("."):fileName.length()) + "." + FORMAT.toLowerCase();ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));return fileName;}/*** 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.* (mkdir如果父目录不存在则会抛出异常)* @param destPath 存放目录*/public static void mkdirs(String destPath) {File file = new File(destPath);if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}/*** 生成二维码(内嵌LOGO)* @param content 内容* @param logoPath LOGO地址* @param destPath 存储地址* @throws Exception*/public static String encode(String content, String logoPath, String destPath) throws Exception {return QRCodeUtil.encode(content, logoPath, destPath, false);}/*** 生成二维码* @param content 内容* @param destPath 存储地址* @param needCompress 是否压缩LOGO* @throws Exception*/public static String encode(String content, String destPath, boolean needCompress) throws Exception {return QRCodeUtil.encode(content, null, destPath, needCompress);}/*** 生成二维码* @param content 内容* @param destPath 存储地址* @throws Exception*/public static String encode(String content, String destPath) throws Exception {return QRCodeUtil.encode(content, null, destPath, false);}/*** 生成二维码(内嵌LOGO)* @param content 内容* @param logoPath LOGO地址* @param output 输出流* @param needCompress 是否压缩LOGO* @throws Exception*/public static void encode(String content, String logoPath, OutputStream output, boolean needCompress)throws Exception {BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);ImageIO.write(image, FORMAT, output);}/*** 生成二维码* @param content 内容* @param output 输出流* @throws Exception*/public static void encode(String content, OutputStream output) throws Exception {QRCodeUtil.encode(content, null, output, false);}/*** 解析二维码* @param file 二维码图片* @return* @throws Exception*/public static String decode(File file) throws Exception {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;}/*** 解析二维码* @param path 二维码图片地址* @return* @throws Exception*/public static String decode(String path) throws Exception {return QRCodeUtil.decode(new File(path));}public static void main(String[] args) throws Exception {String text = "http://www.lianyinkeji.cn";//含Logo,指定二维码图片名QRCodeUtil.encode(text, "E:\\codebase\\zxing\\src\\main\\resources\\logo.png", "E:\\", "qrcode", true);//不含Logo//QRCodeUtil.encode(text, null, "e:\\", true);//含Logo,不指定二维码图片名//QRCodeUtil.encode(text, "e:\\csdn.jpg", "e:\\", true);}}

2. maven依赖

<dependency><groupId>com.google.zxinggroupId><artifactId>coreartifactId><version>3.1.0version>
dependency><dependency><groupId>com.google.zxinggroupId><artifactId>javaseartifactId><version>3.1.0version>
dependency>


推荐阅读
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 本文介绍了Java中Hashtable的clear()方法,该方法用于清除和移除指定Hashtable中的所有键。通过示例程序演示了clear()方法的使用。 ... [详细]
  • 本文介绍了一个Java猜拳小游戏的代码,通过使用Scanner类获取用户输入的拳的数字,并随机生成计算机的拳,然后判断胜负。该游戏可以选择剪刀、石头、布三种拳,通过比较两者的拳来决定胜负。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • JDK源码学习之HashTable(附带面试题)的学习笔记
    本文介绍了JDK源码学习之HashTable(附带面试题)的学习笔记,包括HashTable的定义、数据类型、与HashMap的关系和区别。文章提供了干货,并附带了其他相关主题的学习笔记。 ... [详细]
  • 本文介绍了Swing组件的用法,重点讲解了图标接口的定义和创建方法。图标接口用来将图标与各种组件相关联,可以是简单的绘画或使用磁盘上的GIF格式图像。文章详细介绍了图标接口的属性和绘制方法,并给出了一个菱形图标的实现示例。该示例可以配置图标的尺寸、颜色和填充状态。 ... [详细]
  • 本文讨论了在VMWARE5.1的虚拟服务器Windows Server 2008R2上安装oracle 10g客户端时出现的问题,并提供了解决方法。错误日志显示了异常访问违例,通过分析日志中的问题帧,找到了解决问题的线索。文章详细介绍了解决方法,帮助读者顺利安装oracle 10g客户端。 ... [详细]
  • 本文介绍了如何在给定的有序字符序列中插入新字符,并保持序列的有序性。通过示例代码演示了插入过程,以及插入后的字符序列。 ... [详细]
  • importjava.util.ArrayList;publicclassPageIndex{privateintpageSize;每页要显示的行privateintpageNum ... [详细]
  • 闭包一直是Java社区中争论不断的话题,很多语言都支持闭包这个语言特性,闭包定义了一个依赖于外部环境的自由变量的函数,这个函数能够访问外部环境的变量。本文以JavaScript的一个闭包为例,介绍了闭包的定义和特性。 ... [详细]
author-avatar
xo麦先生
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有