使用Google ZXing生成和解析二维码
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nihaorz</groupId>
<artifactId>zxing</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies> </project>
MatrixToImageWriter.java
import com.google.zxing.common.BitMatrix; import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream; /**
* Created by Nihaorz on 2017/5/9.
*/
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);
}
}
}
BufferedImageLuminanceSource.java
import com.google.zxing.LuminanceSource; import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage; /**
* Created by Nihaorz on 2017/5/9.
*/
public 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;
} @Override
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;
} @Override
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;
} @Override
public boolean isCropSupported() {
return true;
} @Override
public LuminanceSource crop(int left, int top, int width, int height) {
return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
} @Override
public boolean isRotateSupported() {
return true;
} @Override
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 BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
}
}
Test.java
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer; import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Random; /**
* Created by Nihaorz on 2017/5/9.
*/
public class Test { public static void main(String[] args) {
String path = createQrcode("https://github.com/zxing/zxing");
System.out.println("生成的二维码地址:"+path);
String text = decodeQr(path);
System.out.println("扫描二维码得到的文字:"+text);
} public static String createQrcode(String _text){
String qrcodeFilePath = "";
try {
int qrcodeWidth = 256;
int qrcodeHeight = 256;
String qrcodeFormat = "png";
HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(_text, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hints); BufferedImage image = new BufferedImage(qrcodeWidth, qrcodeHeight, BufferedImage.TYPE_INT_RGB);
Random random = new Random();
File QrcodeFile = new File("F:\\qrcode\\" + random.nextInt() + "." + qrcodeFormat);
ImageIO.write(image, qrcodeFormat, QrcodeFile);
MatrixToImageWriter.writeToFile(bitMatrix, qrcodeFormat, QrcodeFile);
qrcodeFilePath = QrcodeFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
return qrcodeFilePath;
} public static String decodeQr(String filePath) {
String retStr = "";
if ("".equalsIgnoreCase(filePath) && filePath.length() == 0) {
return "图片路径为空!";
}
try {
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filePath));
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap bitmap = new BinaryBitmap(binarizer);
HashMap<DecodeHintType, Object> hintTypeObjectHashMap = new HashMap<DecodeHintType, Object>();
hintTypeObjectHashMap.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap, hintTypeObjectHashMap);
retStr = result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return retStr;
} }
参考:
http://www.cnblogs.com/java-class/p/5251690.html
http://blog.csdn.net/gao36951/article/details/41148075
使用Google ZXing生成和解析二维码的更多相关文章
- ZXing 生成、解析二维码图片的小示例
概述 ZXing 是一个开源 Java 类库用于解析多种格式的 1D/2D 条形码.目标是能够对QR编码.Data Matrix.UPC的1D条形码进行解码. 其提供了多种平台下的客户端包括:J2ME ...
- Java使用Zxing生成、解析二维码工具类
Zxing是Google提供的关于条码(一维码.二维码)的解析工具,提供了二维码的生成与解析的方法. 1.二维码的生成 (1).将Zxing-core.jar 包加入到classpath下. (2). ...
- 使用zxing生成和解析二维码
二维码: 是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的: 在代码编制上巧妙的利用构成计算机内部逻辑基础的0和1比特流的概念,使用若干个与二进制相对应的几何 ...
- zxing生成和解析二维码
今天忙了一天的二维码,用了QRcode和ZXing两个开源包.结果发现 ZXing比QRcode更好用一些,它直接可以定义二维码生成图案的大小,而QRcode生成的二维码是根据二维码包含的内容多少来定 ...
- 使用Google提供的ZXing Core,Java生成、解析二维码
1.maven项目中,pom.xml中引入ZXing Core工具包: <!-- https://mvnrepository.com/artifact/com.google.zxing/core ...
- Java生成、解析二维码
今天遇到需求,使用Java生成二维码图片,网搜之后,大神们早就做过,个人总结一下. 目标:借助Google提供的ZXing Core工具包,使用Java语言实现二维码的生成和解析. 步骤如下: 1.m ...
- JAVA中生成、解析二维码图片的方法
JAVA中生成.解析二维码的方法并不复杂,使用google的zxing包就可以实现.下面的方法包含了生成二维码.在中间附加logo.添加文字功能,并有解析二维码的方法. 一.下载zxing的架包,并导 ...
- java生成和解析二维码
前言 现在,二维码的应用已经非常广泛,在线生成器也是诸多,随手生成. 所以就和大家分享一个小案例,用zxing来做一个的二维码生成器,当然这个例子是比较简单,若是写的不好请多多包涵. ZXING项目是 ...
- Java使用QRCode.jar生成与解析二维码
原文V:http://www.cnblogs.com/bigroc/p/7496995.html#3797682 正题:Java使用QRCode.jar生成与解析二维码demo 欢迎新手共勉,大神监督 ...
随机推荐
- TMS-规划图
规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 规划图 ...
- 【thinkPHP框架】Failed opening required 'header.php' include_path='.;c:\php5\pear 终级解决方案
ThinkPHP框架中的某一个php页面,想要去引入其他php页面,结果反复报错,无解. 各种百度,有说是文件权限不够的,也有说配置不对的,反正一个都没有解决这个问题,依然无解. 最终,找到了办法,似 ...
- BAT美团滴滴java面试大纲(带答案版)之三:多线程synchronized
继续面试大纲系列文章. 从这一篇开始,我们进入ava编程中的一个重要领域---多线程!多线程就像武学中对的吸星大法,理解透了用好了可以得道成仙,俯瞰芸芸众生:而滥用则会遭其反噬. 在多线程编程中要渡的 ...
- [WPF]如何使用代码创建DataTemplate(或者ControlTemplate)
1. 前言 上一篇文章([UWP]如何使用代码创建DataTemplate(或者ControlTemplate))介绍了在UWP上的情况,这篇文章再稍微介绍在WPF上如何实现. 2. 使用Framew ...
- 用commander.js构建自己的脚手架工具
随着前端技术的发展,工程化逐渐成为了一种趋势.但在实际开发时,搭建项目是一件很繁琐的事情,尤其是在对一个框架的用法还不熟悉的时候.于是很多框架都自带一套脚手架工具,在初始化前端项目的时候就可以不用自己 ...
- hdu 5584 LCM Walk
没用运用好式子...想想其实很简单,首先应该分析,由于每次加一个LCM是大于等于其中任何一个数的,那么我LCM加在哪个数上面,那个数就是会变成大的,这样想,我们就知道,每个(x,y)对应就一种情况. ...
- Spring AOP详细介绍
AOP称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等待,Struts2的拦截器设计就是基于AOP的思想,是个比较经典的例子. 一 AOP的基本概念 (1)Asp ...
- Eclipse启动错误JVM terminated. exit code 1解决方法
现象: 前一天eclipse还用得好好的,但今天就不能用了,怎么回事? 解决方案: 请先参考其它网络资料:http://www.baidu.com/s?wd=eclipse+jvm+terminate ...
- tortoisegit密钥与git密钥配置
在客户端生成密钥并将公钥上传到服务器可以避免每次连接git服务器都要登录的尴尬. 但git的私钥是不能直接用在tortoisegit上的,需要用tortoisegit的puttygen转换一下,详细过 ...
- sqlserver笔记
表结构: 一,字段类型sqlserver jdbc java char char Stringnchar nchar Stringvarchar varchar Stringnvarchar nvar ...