引言
在这篇博客中关于二维码的基本原理先不做介绍,先介绍我们怎样利用java语言实现二维码的生成,现在二维
码在我们生活中已经非常常见了,一言不合就扫码!所以对于我们这帮程序猿来说,需要研究一把这个东西是怎么生
成,今天小编就给大家介绍一下,怎样一步一步生成二维码的。
在这给大家介绍两种二维码,也是我们在生活中非常常见的两种,一种就是中间没有LOGO的二维码,一种是中间
带有logo的,当然现在第二种带有logo的二维码是非常常见的。
我们需要引用两个jar包:core-3.1.0.jar和Qrcode_swetake.jar
第一个java包也即是zxing.jar 包, 我这里用的是3.0 版本的core包,是Goole开发的,第二个jar包是用来解码的
下面是整个demo的目录结构
核心类(BufferedImageLuminanceSource)代码:
package com.dmsd.demo;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import com.google.zxing.LuminanceSource;
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