一、什么是二维码:
二维码 (2-dimensional bar code),是用某种特定的几何图形按一定规律在平面(二维方向上)
分布的黑白相间的图形记录数据符号信息的。
二、常用的码制
Data Matrix, Maxi Code, Aztec, QR Code, Vericode, PDF417, Ultracode, Code 49, Code 16K等。
三、为什么叫二维码
二维码的名称是相对与一维码来说的:
比如以前的条形码,只有横向的竖条状信息,所以也叫“一维码”。
二维码呢,则是横向纵向都有信息,所有叫“二维码”。
二维码优点有:
存储的数据量更大;可以包含数字、字符,及中文文本等混合内容;有一定的容错性(在部分损坏以后可以正常读取);空间利用率高等。
二维码中,最流行莫过于QR CODE。
四、二维码为什么是黑白相间的?
因为黑色表示二进制的“1”,白色表示二进制的“0”。
我们之所以对二维码进行扫描能读出那么多信息,就是因为这些信息被编入了二维码之中。
制作二维码输入的信息可以分成三类:
文本信息,比如名片信息;
字符信息,比如网址、电话号码;
图片信息,甚至还可以包括简短的视频。
数据信息是怎么被编入的呢?
信息输入后,首先要选择一种信息编码的码制。现在常见的二维码都是以QR码作为编码的码制。QR码是矩阵式二维码,它是在一个矩形空间内,通过黑、白像素在矩阵中的不同分布,来进行编码的。我们知道电脑使用二进制(0和1)数来贮存和处理数据,而在二维码中,用黑白矩形表示二进制数据我们肉眼能看到的黑色表示的是二进制“1”,白色表示二进制的“0”,黑白的排列组合确定了矩阵式二维条码的内容,以便于计算机对二维码符号进行编码和分析。
五、QR CODE 介绍
QR(Quick-Response) code是被广泛使用的一种二维码,解码速度快。它可以存储多用类型
如上图时一个qrcode的基本结构,其中:
位置探测图形、位置探测图形分隔符、定位图形:用于对二维码的定位,对每个QR码来说,位置都是固定存在的,只是大小规格会有所差异;
校正图形:规格确定,校正图形的数量和位置也就确定了;
格式信息:表示改二维码的纠错级别,分为L、M、Q、H;
版本信息:即二维码的规格,QR码符号共有40种规格的矩阵(一般为黑白色),从21×21(版本1),到177×177(版本40),每一版本符号比前一版本 每边增加4个模块。
数据和纠错码字:实际保存的二维码信息,和纠错码字(用于修正二维码损坏带来的错误)。
简要的编码过程:
- 数据分析:确定编码的字符类型,按相应的字符集转换成符号字符; 选择纠错等级,在规格一定的条件下,纠错等级越高其真实数据的容量越小。
- 数据编码:将数据字符转换为位流,每8位一个码字,整体构成一个数据的码字序列。其实知道这个数据码字序列就知道了二维码的数据内容。
QR码可以从任意方向读取:
QR码从360°任一方向均可快速读取。其奥秘就在于QR码中的3处定位图案,可以帮助QR码不受背景样式的影响,实现快速稳定的读取。
提示:
QR码是日本产的二维码,因此非常适合处理日文字母和汉字。QR码字集规格定义是按照日本标准“JIS第一级和第二级的汉字”制定的,因此在日语处理方面,每一个全角字母和汉字都用13比特的数据处理,效率较高,与其他二维码相比,可以多存储20%以上的信息。
六、QR码纠错功能
QR码具有“纠错功能”。即使编码变脏或破损,也可自动恢复数据。这一“纠错能力”具备4个级别,用户可根据使用环境选择相应的级别。调高级别,纠错能力也相应提高,但由于数据量会随之增加(对应二维码里包含的错误校验信息增加),编码尺寸也也会变大,图形也会变密。
用户应综合考虑使用环境、编码尺寸等因素后选择相应的级别。 在工厂等容易沾染赃物的环境下,可以选择级别Q或H,在不那么脏的环境下,且数据量较多的时候,也可以选择级别L。一般情况下用户大多选择级别M(15%)。
那是怎么修正错误呢?
比如我要存一百个数字,那可以额外加一个这一百个数字的和,如果有一个数字缺失,那根据这个和求出,这个就是百分之一的可被修正。如果想两个缺失能被复原就需要再加一些参数。所以信息量就增加了,对应图形就越来越密了。
七、QR码的信息量和版本
QR码设有1到40的不同版本,每个版本都具备固有的码元结构(码元数)。
码元是指构成QR码的方形黑白点。
码元结构是指二维码中的码元数。从版本1(21码元×21码元)开始,在纵向和横向各自以4码元为单位递增,一直到版本40(177码元×177码元)。
QR码的各个版本结合数据量、字符类型和纠错级别,均设有相对应的最多输入字符数。也就是说,如果增加数据量,则需要使用更多的码元来组成QR码,QR码就会变得更大,更密。
八、具体实现
示例图:
【该二维码将跳转百度页面】
【其中图片由两部分构成,二维码+中间“评”字图片】
接下来直接复制粘贴代码就可以
1、QRCodeUtil 工具类
package com.cnpc.dj.party.util;
import com.google.zxing.*;
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;
public class QRCodeUtil {
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;
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) { // 压缩LOGO
if (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;
}
// 插入LOGO
Graphics2D 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, boolean
* needCompress) throws Exception { QRCodeUtil.encode(content, null, destPath,
* needCompress); }
*/
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;
}
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;
}
public static String decode(String path) throws Exception {
return QRCodeUtil.decode(new File(path));
}
}
2、BufferedImageLuminanceSource
package com.cnpc.dj.party.util;
import com.google.zxing.LuminanceSource;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
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;
}
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 BufferedImageLuminanceSource(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 BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
}
}
以上代码定义了一个名为BufferedImageLuminanceSource的类,它继承自LuminanceSource类。该类表示一个基于BufferedImage的亮度源。
其中包含了构造方法和一些方法用于获取行、矩阵、裁剪和旋转等操作。构造方法接受一个BufferedImage对象作为参数,并可以指定裁剪区域的位置和大小。在构造方法中,对图像进行了处理,将透明像素(alpha值为0)替换为白色。同时也创建了一个新的灰度图像对象。
getRow方法用于获取指定行的像素数据,getMatrix方法用于获取整个图像的像素数据。isCropSupported和isRotateSupported方法返回true,表示支持裁剪和旋转操作。crop方法用于裁剪图像,rotateCounterClockwise方法用于将图像逆时针旋转90度。
总体来说,这段代码实现了基于BufferedImage的亮度源类,提供了对图像进行操作的方法。
3、运行结果
package com.cnpc.dj.party.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import sun.misc.BASE64Encoder;
public class QRCodeGenerator {
// private static final String QR_CODE_IMAGE_PATH = "C:/Users/Administrator/Desktop/xsCRID2QwK.png";
//
// private static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
// QRCodeWriter qrCodeWriter = new QRCodeWriter();
//
// BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
//
// Path path = FileSystems.getDefault().getPath(filePath);
//
// MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
//
// }
public static byte[] getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
byte[] pngData = pngOutputStream.toByteArray();
return pngData;
}
public static String getBase64(String url) {
byte[] qrcode = null;
try {
qrcode = QRCodeGenerator.getQRCodeImage(url, 360, 360);
} catch (WriterException e) {
System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
}
String str = new BASE64Encoder().encode(qrcode);
return str;
}
public static void main(String[] args) throws Exception {
try {
// 存放在二维码中的内容
String text = "https://www.baidu.com";
// 嵌入二维码的图片路径
String imgPath = "C:/Users/Administrator/Desktop/a.png";
// 生成的二维码的路径及名称
String destPath = "C:/Users/Administrator/Desktop/b.png";
//生成二维码
QRCodeUtil.encode(text, imgPath, destPath, true);
// 解析二维码
String str = QRCodeUtil.decode(destPath);
// 打印出解析出的内容
System.out.println(str);
} catch (WriterException e) {
System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
} catch (IOException e) {
System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
}
}
}