java google.zxing解析二维码工具类

文章目录

  • pom
  • 代码
  • 解析用例
  • 生成二维码用例

pom

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

代码

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.junit.Test;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
public class QRCodeUtil extends LuminanceSource {private final BufferedImage IMAGE;private final int LEFT;private final int TOP;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;public QRCodeUtil(BufferedImage image) {this(image, 0, 0, image.getWidth(), image.getHeight());}public QRCodeUtil(BufferedImage image, int left, int top, int width, int height) {super(width, height);int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();if (left + width > sourceWidth || top + height > sourceHeight) {throw new IllegalArgumentException("Crop rectangle does not fit within image data.");}for (int y = top; y < top + height; y++) {for (int x = left; x < left + width; x++) {if ((image.getRGB(x, y) & 0xFF000000) == 0) {image.setRGB(x, y, 0xFFFFFFFF); // = white}}}this.IMAGE = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);this.IMAGE.getGraphics().drawImage(image, 0, 0, null);this.LEFT = left;this.TOP = top;}public byte[] getRow(int y, byte[] row) {if (y < 0 || y >= getHeight()) {throw new IllegalArgumentException("Requested row is outside the image: " + y);}int width = getWidth();if (row == null || row.length < width) {row = new byte[width];}IMAGE.getRaster().getDataElements(LEFT, TOP + y, width, 1, row);return row;}public byte[] getMatrix() {int width = getWidth();int height = getHeight();int area = width * height;byte[] matrix = new byte[area];IMAGE.getRaster().getDataElements(LEFT, TOP, width, height, matrix);return matrix;}public boolean isCropSupported() {return true;}public LuminanceSource crop(int left, int top, int width, int height) {return new QRCodeUtil(IMAGE, this.LEFT + left, this.TOP + top, width, height);}public boolean isRotateSupported() {return true;}public LuminanceSource rotateCounterClockwise() {int sourceWidth = IMAGE.getWidth();int sourceHeight = IMAGE.getHeight();AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);Graphics2D g = rotatedImage.createGraphics();g.drawImage(IMAGE, transform, null);g.dispose();int width = getWidth();return new QRCodeUtil(rotatedImage, TOP, sourceWidth - (LEFT + width), getHeight(), width);}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) { // 压缩LOGOif (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;}// 插入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();}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, String destPath) throws Exception {QRCodeUtil.encode(content, imgPath, destPath, false);}public static void encode(String content, String destPath) throws Exception {QRCodeUtil.encode(content, null, destPath, false);}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);}public static String decode(File file) throws Exception {BufferedImage image;image = ImageIO.read(file);if (image == null) {return null;}QRCodeUtil source = new QRCodeUtil(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;}public static String decode(String path) throws Exception {return QRCodeUtil.decode(new File(path));}}

解析用例

QRCodeUtil.decode(File file)  传入二维码图片文件对象
QRCodeUtil.decode(String filePath) 传入二维码图片文件路径

生成二维码用例

encode(String content, String imgPath, String destPath, boolean needCompress) 
content: 需要写入二维码中的数据
imgPath: 二维码  中嵌入的图片路径 (就是 微信用户二维码中的头像  里面有你的头像的那种二维码)
destPath:生成后的路径
needCompress:是否需要压缩  true
-----------------------------------------------------------------------------------------
encode(String content, String destPath)
content:需要写入二维码中的数据
destPath:生成后的路径
-----------------------------------------------------------------------------------------
encode(String content, String imgPath, boolean needCompress)
返回BufferedImage对象 
content: 需要写入二维码中的数据
imgPath: 二维码  中嵌入的图片路径 (就是 微信用户二维码中的头像  里面有你的头像的那种二维码)
needCompress:是否需要压缩  true
返回的BufferedImage对象并没有将图片写入磁盘 我们可以调用下面的方法  写入磁盘
ImageIO.write(image, FORMAT_NAME, new File(destPath));
image:BufferedImage对象
FORMAT_NAME:图片扩展名 JPG
-----------------------------------------------------------------------------------------public static void main(String[] args) throws Exception {String content = "孙张熠!!";
//        // 嵌入二维码的图片路径String imgPath = "C:\\Users\\Administrator\\Desktop\\image\\20180923010802416.jpg";
//        // 生成的二维码的路径及名称String destPath = "D:\\hello.jpg";
//        //生成二维码ImageIO.write(QRCodeUtil.encode(content, imgPath, true), "jpg", new File(destPath));}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/200647.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

通俗理解Jenkins是什么?

目录 通俗理解 Jenkins是什么&#xff1f; 通俗理解 假设你有一个软件项目&#xff0c;多个开发者在一起写代码。每当有人提交新的代码时&#xff0c;你想要自动地构建、测试这些代码&#xff0c;确保它们没有引入问题。 Jenkins就像一个聪明的助手&#xff0c;会在有人提交…

【数据仓库-10】-- 数据仓库、数据湖和湖仓一体对比

目录 1 数据仓库与数据库的对比 2 数据湖与数据仓库的对比 3 数据仓库、数据湖和湖仓一体

检查 `/var` 是否有自己的独立分区

要检查 /var 是否有自己的独立分区&#xff0c;您可以使用以下方法&#xff1a; 1. 使用 df 命令 df 命令&#xff08;磁盘文件系统&#xff09;可以用来报告文件系统的磁盘空间使用情况。要查看 /var 的情况&#xff0c;请运行&#xff1a; df -h /var这个命令会显示 /var …

在AWS Lambda中使用FFmpeg处理m3u8视频流

大纲 1 部署有FFmpeg功能的Lambda环境1.1 部署层1.2 部署代码1.2.1 FFmpeg指令1.2.2 代码 2 配置Lambda角色权限2.1 选择角色类型2.2 设置权限2.3 保存角色2.4 绑定角色 参考文献 在直播里领域&#xff0c;我们经常需要对视频流进行处理。FFmpeg则是该领域中处理的利器。这篇文…

根文件系统的开机自启动测试

一. 简介 本文在之前制作的根文件系统可以正常运行的基础上进行的&#xff0c;继上一篇文章地址如下&#xff1a; 完善根文件系统-CSDN博客 在前面测试软件hello 运行时&#xff0c;都是等 Linux 启动进入根文件系统以后手动输入 “./hello” 命令 来完成的。 我们一般做好产…

C++:一个函数返回值的小问题

今天一位同学问了我这样一个问题&#xff1a; int& getDState() { return _dstate; } int getDState() { return _dstate; }这两个函数有什么区别&#xff1f; 这两个返回一个名为 _dstate 的成员变量或变量。函数的返回类型不同&#xff0c;在C中是不允许的&#xff0c;…

Python计算方差

方差可以反应变量的离散程度&#xff0c;是因为它度量了数据点与均值的差异。方差是每个数据点与均值的差的平方和的平均值&#xff0c;它可以反映数据点在均值附近的分布情况。如果方差较小&#xff0c;说明数据点更加集中在均值附近&#xff0c;离散程度较小&#xff1b;如果…

uniapp微信小程序分包,小程序分包

前言&#xff0c;都知道我是一个后端开发、所以今天来写一下uniapp。 起因是美工给我的切图太大&#xff0c;微信小程序不让了&#xff0c;在网上找了一大堆分包的文章&#xff0c;我心思我照着写的啊&#xff0c;怎么就一直报错呢&#xff1f; 错误原因 tabBar的页面被我放在分…

【JSD1209考试】题目与解答

选择题 在Java Applet程序中&#xff0c;如果对发生的事件做出响应和处理的时候&#xff0c;应该使用的语句是&#xff1f; ( C ) &#xff08;1分&#xff09; A. import java.awt.*;B. import java.applet.*;C. import java.awt.event.*;D. import java.io.*; 以下返回true的…

【从零开始学习JVM | 第一篇】快速了解JVM

前言&#xff1a; 在探索现代软件开发的丰富生态系统时&#xff0c;我们不可避免地会遇到一个强大而神秘的存在——Java虚拟机&#xff08;JVM&#xff09;。作为Java语言最核心的组成之一&#xff0c;JVM已经超越了其最初的设计目标&#xff0c;成为一个多语言的运行平台&…

JavaScript包管理器分类和区别

一、JavaScript包管理器分类 NPMYarnPNPMBun 二、包管理器的区别 1、NPM 是Node.js的默认包管理器&#xff0c;默认随Node.js一起安装&#xff0c;无需额外配置。 npm2 采用简单的递归依赖方法&#xff0c;最后形成高度嵌套的依赖树。然后就会造成如下问题&#xff1a;重复依…

【JavaSE】网络编程(学习笔记)

一、网络编程概述 网络编程&#xff1a;网络互联的计算机实现数据交换 1、网络编程三要素 1&#xff09;IP IP&#xff1a;网络中设备的唯一标识 cmd -> ipconfig&#xff1a;查看本机ip cmd -> ping ip地址&#xff1a;检查网络是否连通 127.0.0.1&#xff1a;回送地…

Ubuntu环境下使用nginx实现强制下载静态资源

安装Nginx sudo apt update sudo apt install nginx关闭防火墙 sudo ufw allow Nginx HTTP修改nginx配置 cd /etc/nginx/conf.d vi nginx.conf在http配置中添加(/your path/为需要下载的文件路径) server {listen 80;server_name localhost;location / {root /your path/…

convert_from_pinhole_camera_parameters 失败

函数convert_from_pinhole_camera_parameters 在0.17版本中有bug。 应该说是&#xff0c;直接使用pip install open3d 的0.17版本有问题&#xff0c;在git code中已经修复&#xff0c;需要下载后用pip安装。希望pip赶紧更新。。。。 参考&#xff1a; Fix the pybind refer…

WPS Office JS宏实现批量处理Word中的标题和正文的样式

该篇讲解下word文档中的标题和正文批量修改样式&#xff0c;如下图&#xff1a; 前面一篇已讲解了WPS Office宏编辑器操作方法&#xff0c;这里不细讲了&#xff0c;如有不清楚可以查看该篇&#xff1a;https://blog.csdn.net/jiciqiang/article/details/134653657?spm1001.20…

Install4J安装界面中如何使用脚本找到依赖程序XShell的安装位置

前言 写了一个工具, 使用Install4j打包, 但因为需要用到XShell, 所以希望在安装界面能够提前让用户配置好XShell的安装位置, 所以对Install4j的安装界面需要自定义, 后期在程序中直接过去安装位置就可以正常使用. 调研 和git-bash不一样, 安装版的XShell没有在注册表里存储安…

Ubuntu系统下使用apt-get安装Redis

记录一下Ubuntu20.04 64位系统下使用apt-get安装Redis 首先检查一下系统是否安装过redis whereis redismywmyw-K84HR:~$ whereis redis redis: mywmyw-K84HR:~$ 更新软件包 sudo apt-get update -y安装redis sudo apt-get install redis-server -ymywmyw-K84HR:~$ sudo apt…

数字ic设计技巧:添加debug信号

数字ic设计技巧&#xff1a;添加debug信号 文章目录 数字ic设计技巧&#xff1a;添加debug信号1. 握手方式读取数据的debug信号o_wait_read2. FIFO的空满信号3. 输入错误4. 多状态机的debug信号5. 使用FIFO记录log 在数字ic设计的过程中&#xff0c;我们常常通过添加一些debug信…

Java常见CodeReview及编码规范

鉴于自己的开发经验,以及常见容易产生bug及性能问题的点做个记录. 1.数据库 如果开发人员的经验不足,Java通过ORM(Mybatis)对数据库的操作的性能问题比较隐蔽.因为不压测或者异常case没发生的时候一般发现不了问题.特别是异常case发生的时候. 除配置表以外的sql都要经过expl…

LINQ【C#】

1LINQ概述&#xff1a; 集成查询&#xff0c;在对象领域和数据领域之间架起了一座桥梁。 LINQ主要由3部分组成&#xff1a;LINQ to ADO.NET、LINQ to Objects和LINQ to XML。其中&#xff0c;LINQ to ADO.NET可以分为两部分&#xff1a;LINQ to SQL 和LINQ to DataSet。 var…