使用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 欢迎新手共勉,大神监督 ...
随机推荐
- vue引入css的两种方式
方案1.在main.js中引入方式 import '@/assets/css/reset.css' 方案2.在.vue文件的<style/>标签里面引入 @import &qu ...
- 从源码看Spring Security之采坑笔记(Spring Boot篇)
一:唠嗑 鼓捣了两天的Spring Security,踩了不少坑.如果你在学Spring Security,恰好又是使用的Spring Boot,那么给我点个赞吧!这篇博客将会让你了解Spring S ...
- .NetCore简单学习图谱
一.学习途径 学习.netcore的最佳途径在哪里,无疑是微软官方.netCore指南.它覆盖十分全面,就目前网上经常看到的各种文章都能在微软处找到类似文章,堪称.netcore的百科全书.所以我利用 ...
- Redis中单机数据库的实现
1. 内存操作层 zmalloc 系接口 redis为了优化内存操作, 封装了一层内存操作接口. 默认情况下, 其底层实现就是最简朴的libc中的malloc系列接口. 如果有定制化需求, 可以通过配 ...
- Redux与它的中间件:redux-thunk,redux-actions,redux-promise,redux-saga
序言 这里要讲的就是一个Redux在React中的应用问题,讲一讲Redux,react-redux,redux-thunk,redux-actions,redux-promise,redux-sag ...
- Jenkins ChangeLog
Log changes in Jenkins - Stack Overflowhttps://stackoverflow.com/questions/13631145/log-changes-in-j ...
- html5-attr和prop
###1.什么是attrbute和property attribute(attr) html标签的预定义属性 checked html标签的自定义属性 a eg: <input ...
- C#设计模式之3:观察者模式
C#中已经实现了观察者模式,那就是事件,事件封装了委托,使得委托的封装性更好,在类的内部定义事件,然后在客户端对事件进行注册: public class Subject { public event ...
- vue实现双向数据绑定之Object.defineProperty()篇
前言 vue.js中使用ES5的Object.defineProperty()实现数据的双向绑定 Object.defineProperty()原理 Object.defineProperty()可以 ...
- array_filter与array_map
php数组array_filter函数和array_slice函数:<?php /* array_filter()用回调函数过滤数组中的单元 array_filter(array,functio ...