Zxing是一个开源的 用Java实现的多种格式的1D/2D条码图像处理库,可以生成、解析二维码。

二维码它就是把一段纯文本用图形样式转换出来了,以便于快速扫描读出

首先,新建一个Java工程,然后导入需要的Zxing jar包,
工程结构如下:

1.二维码生成

1.1将源码中关于二维码生成的类拷贝进来,

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import com.google.zxing.common.BitMatrix;public final class MatrixToImageWriter {private static final int BLACK = 0xFF000000;private static final int WHITE = 0xFFFFFFFF;private MatrixToImageWriter() {}public static BufferedImage toBufferedImage(BitMatrix matrix) {int width = matrix.getWidth();int height = matrix.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, matrix.get(x, y) ? BLACK : WHITE);}}return image;}public static void writeToFile(BitMatrix matrix, String format, File file)throws IOException {BufferedImage image = toBufferedImage(matrix);if (!ImageIO.write(image, format, file)) {throw new IOException("Could not write an image of format "+ format + " to " + file);}}public static void writeToStream(BitMatrix matrix, String format,OutputStream stream) throws IOException {BufferedImage image = toBufferedImage(matrix);if (!ImageIO.write(image, format, stream)) {throw new IOException("Could not write an image of format "+ format);}}
}

1.2在main方法中编写实现二维码生成的方法

private static void generateCode() {try {String content = "http://www.baidu.com";String path = "C:\\Users\\Dong\\Desktop\\testImage";File dir = new File(path);if (!dir.exists()) {dir.mkdir();}MultiFormatWriter multiFormatWriter = new MultiFormatWriter();Map hints = new HashMap();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");BitMatrix bitMatrix = multiFormatWriter.encode(content,BarcodeFormat.QR_CODE, 400, 400, hints);File file1 = new File(dir, "url.png");MatrixToImageWriter.writeToFile(bitMatrix, "png", file1);System.out.println("二维码生成成功!");} catch (Exception e) {e.printStackTrace();}}

2.二维码解析

2.1 将源码中关于二维码解析的类拷贝进来

import com.google.zxing.LuminanceSource;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;public final class BufferedImageLuminanceSource extends LuminanceSource {private final BufferedImage image;private final int left;private final int top;public BufferedImageLuminanceSource(BufferedImage image) {this(image, 0, 0, image.getWidth(), image.getHeight());}public BufferedImageLuminanceSource(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;}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic boolean isCropSupported() {return true;}@Overridepublic LuminanceSource crop(int left, int top, int width, int height) {return new BufferedImageLuminanceSource(image, this.left + left,this.top + top, width, height);}@Overridepublic boolean isRotateSupported() {return true;}@Overridepublic 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 BufferedImageLuminanceSource(rotatedImage, top, sourceWidth- (left + width), getHeight(), width);}}

2.1 编写实现二维码解析的方法

private static void decode() {try {MultiFormatReader formatReader = new MultiFormatReader();String filePath = "C:\\Users\\Dong\\Desktop\\testImage\\url.png";File file = new File(filePath);BufferedImage image = ImageIO.read(file);LuminanceSource source = new BufferedImageLuminanceSource(image);Binarizer binarizer = new HybridBinarizer(source);BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);Map hints = new HashMap();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");Result result = formatReader.decode(binaryBitmap, hints);System.out.println("result = " + result.toString());System.out.println("resultFormat = " + result.getBarcodeFormat());System.out.println("resultText = " + result.getText());} catch (Exception e) {e.printStackTrace();}}

解析结果

参考:
- http://www.cnblogs.com/jtmjx/archive/2012/06/18/2545209.html
- https://www.zhihu.com/question/21096632

源码下载

Java---利用Zing生成二维码、解析二维码相关推荐

  1. Java利用poi生成word(包含插入图片,动态表格,行合并)

    Java利用poi生成word(包含插入图片,动态表格,行合并) 测试模板样式: 图表 1 Word生成结果: 图表 2 需要的jar包:(具体jar可自行去maven下载) Test测试类: imp ...

  2. 【深度学习模型】智云视图中文车牌识别源码解析(二)

    [深度学习模型]智云视图中文车牌识别源码解析(二) 感受 HyperLPR可以识别多种中文车牌包括白牌,新能源车牌,使馆车牌,教练车牌,武警车牌等. 代码不可谓不混乱(别忘了这是职业公司的准产品级代码 ...

  3. Java利用Zxing生成二维码及解析二维码内容

    前言 Java 操作二维码的开源项目很多,如 SwetakeQRCode.BarCode4j.Zxing 等等 本篇文章是介绍利用Zxing来生成二维码图片在web网页上展示,同时解析二维码图片. Z ...

  4. java利用zxing生成二维码

    什么是ZXing? ZXing是一个开源的,用Java实现的多种格式的1D/2D条码图像处理库. 利用ZXing这个工具库来生成二维码,具体操作如下: 引入相关资源包 <dependency&g ...

  5. Java 将文本内容、网址 ;生成二维码 解析二维码

    准备:生成带logo的二维码时,logo图片必须存在:不存在则生成无logo的二维码. 1.建立Maven项目,并引入jar包. <dependency>     <groupId& ...

  6. android网络框架retrofit源码解析二

    注:源码解析文章参考了该博客:http://www.2cto.com/kf/201405/305248.html 前一篇文章讲解了retrofit的annotation,既然定义了,那么就应该有解析的 ...

  7. Kubernetes学习笔记之Calico CNI Plugin源码解析(二)

    女主宣言 今天小编继续为大家分享Kubernetes Calico CNI Plugin学习笔记,希望能对大家有所帮助. PS:丰富的一线技术.多元化的表现形式,尽在"360云计算" ...

  8. Mobx 源码解析 二(autorun)

    前言 我们在Mobx 源码解析 一(observable)已经知道了observable 做的事情了, 但是我们的还是没有讲解明白在我们的Demo中,我们在Button 的Click 事件中只是对ba ...

  9. erlang下lists模块sort(排序)方法源码解析(二)

    上接erlang下lists模块sort(排序)方法源码解析(一),到目前为止,list列表已经被分割成N个列表,而且每个列表的元素是有序的(从大到小) 下面我们重点来看看mergel和rmergel ...

  10. Thrift源码解析(二)序列化协议

    概述 对于一个RPC框架,定义好网络数据的序列化协议是最基本的工作,thrift的序列化协议主要包含如下几种: TBinaryProtocol TCompactProtocol TJSONProtoc ...

最新文章

  1. [JAVA EE]常用的实体类注解
  2. 防sql注入Replace区分大小写
  3. 叙述无保密机制的rsa签名过程_安全系列之——RSA的公钥私钥有多少人能分的清楚?RSA的签名验签与加密解密如何使用公私钥?...
  4. HDU5120 - Intersection
  5. 资深大牛推荐学习路线建议
  6. TCP协议端口状态说明:CLOSE-WAIT、TIME_WAIT 、LISTENING、SYN_SENT、ESTABLISHED、LAST_ACK、CLOSED
  7. common java socket,JAVA I/O(四)网络Socket和ServerSocket
  8. docker和数据卷问题探究
  9. VMware虚拟机安装系统
  10. 声音存储空间计算公式_音频文件存储容量计算
  11. Vue中的SEO优化
  12. 不靠谱的InetAddress.isReachable,解决办法
  13. vue中使用微信jssdk语音聊天功能
  14. 我把csdn版权标志隐藏了.
  15. 【PCIe 5.0 - 1】PCIe Link属性
  16. Spring security开发权限管理系统(一)
  17. 高德地图在H5页面中的使用(VUE)
  18. 汇编语言---指令格式和基本语法
  19. Ubuntu 下安装Chrom浏览器
  20. virtualbox虚拟机系统网卡设置,既能上网,又能独立ip相互访问

热门文章

  1. 武汉大学计算机研究生导师,武汉大学计算机学院导师简介-丁立新
  2. Northwind 数据库 多版本
  3. Java常用命令与参数设置
  4. Arduino UNO驱动液晶屏TFT_LCD_ST7789v
  5. 考研基础高等数学笔记
  6. 通过代理下载Google Code
  7. 喀秋莎Camtasia Studio微视频录制工具使用指南
  8. CMMB手机电视自毁长城?
  9. java mybatisplus Error parsing time stamp
  10. linux应用程序故障排查,为Linux应用程序排查故障的另类方法