一步一步用 java 设计生成二维码
在物联网的时代,二维码是个很重要的东西了,现在无论什么东西都要搞个二维码标志,唯恐落伍,就差人没有用二维码识别了。也许有一天生分证或者户口本都会用二维码识别了。今天心血来潮,看见别人都为自己的博客添加了二维码,我也想搞一个测试一下.
主要用来实现两点:
1. 生成任意文字的二维码.
2. 在二维码的中间加入图像.
一、准备工作。
准备QR二维码3.0版本的core包和一张jpg图片。
下载QR二维码包。
首先得下载zxing.jar 包, 我这里用的是3.0版本的core包
下载地址:现在已经迁移到了github:https://github.com/zxing/zxing/wiki/Getting-Started-Developing,
当然你也可以从maven仓库下载jar包:http://central.maven.org/maven2/com/google/zxing/core/
二、程序设计
1、启动eclipse,新建一个java项目,命好项目名(本例取名为QRCodeSoft)。点下一步:
2、导入zxing.jar包, 我这里用的是3.0版本的core包:点“添加外部JAR(X)…”。
3、新建两个类,分别是:
BufferedImageLuminanceSource.java
QRCodeUtil.java
关键代码在于:BufferedImageLuminanceSource.java和QRCodeUtil.java, 其中测试的main方法位于QRCodeUtil.java 中。
BufferedImageLuminanceSource.java程序代码:
package qrcodesoft;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import com.google.zxing.LuminanceSource;
public class BufferedImageLuminanceSource extends LuminanceSource{
privatefinal BufferedImage image;
privatefinal int left;
privatefinal int top;
publicBufferedImageLuminanceSource(BufferedImage image) {
this(image,0, 0, image.getWidth(), image.getHeight());
}
publicBufferedImageLuminanceSource(BufferedImage image, int left,
int top, intwidth, int height) {
super(width,height);
intsourceWidth = image.getWidth();
intsourceHeight = image.getHeight();
if (left +width > sourceWidth || top + height > sourceHeight) {
throw newIllegalArgumentException(
"Croprectangle 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;
}
publicbyte[] getRow(int y, byte[] row) {
if (y < 0|| y >= getHeight()) {
throw newIllegalArgumentException(
"Requestedrow is outside the image: " + y);
}