常用的二维码生成的方法中有日本人写的QR和谷歌提供的zxing,生成的常见的方形的二维码 。
项目中用到的jar包,在博文下面的分享的项目源码中的lib目录下。可自行下载。
1.google提供的zxing
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.EncodeHintType;
import javax.imageio.ImageIO;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.BarcodeFormat;
public class QRCodeUtil {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
public void GenerateQRCode(String path,String content) {
int width = 300;
int height = 300;
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// hints.put(EncodeHintType.MARGIN, 2);
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, width, height, hints);
//高版本的jdk可以直接用这个方法,我的jdk1.6没有Path这个类
//MatrixToImageWriter.writeToPath(bitMatrix, "png", new File(path).toPath());
BufferedImage image=toBufferedImage(bitMatrix);
ImageIO.write(image, "bmp", new File(path));
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_BYTE_GRAY);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
bufferedImage.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return bufferedImage;
}
public void DecodeQRCode(String filePath){
BufferedImage image;
try {
image = ImageIO.read(new File(filePath));
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result=new MultiFormatReader().decode(binaryBitmap, hints);
System.out.println("图片中内容: "+result);
System.out.println("图片中格式:"+ result.getBarcodeFormat());
} catch (IOException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String content = "http://www.baidu.com";
String path = "d:/java/img.bmp";
new QRCodeUtil().GenerateQRCode(path,content);
new QRCodeUtil().DecodeQRCode(path);
}
}
生成的二维码如下:(扫码会跳到我们设置的百度首页)
2.QR方法
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.imageio.ImageIO;
import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.exception.DecodingFailedException;
import com.swetake.util.Qrcode;
public class QRCodeUtil {
public static void main(String[] args) throws Exception {
String content = "http://www.baidu.com";
String path = "d:/java/img2.bmp";
new QRCodeUtil().GeneratorQRCode(content, path);
new QRCodeUtil().DecodeQRImg(path);
}
public void GeneratorQRCode(String content,String path) throws IOException{
Qrcode x=new Qrcode();
x.setQrcodeErrorCorrect('M');//纠错等级
x.setQrcodeEncodeMode('B');//N代表数字,A代表a-Z,B代表其他字符
x.setQrcodeVersion(7);//版本
int width = 67 + 12 * (7 - 1);//设置二维码的大小公式:67 + 12 * (version - 1)
int height = 67 + 12 * (7 - 1);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D gs = bufferedImage.createGraphics();
gs.setBackground(Color.WHITE);
gs.setColor(Color.BLACK);
gs.clearRect(0, 0, width, height);//清除画板的内容
int pixoff = 2;//添加一个偏移量
byte[] d = content.getBytes("utf-8");
if (d.length>0 && d.length <120){
boolean[][] s = x.calQrcode(d);
for (int i=0;i<s.length;i++){
for (int j=0;j<s.length;j++){
if (s[j][i]) {
gs.fillRect(j*3 + pixoff,i*3 + pixoff,3,3);
}
}
}
}
gs.dispose();
bufferedImage.flush();
ImageIO.write(bufferedImage, "png", new File(path));
}
public void DecodeQRImg(String path){
String result;
try {
//读取验证码图片
BufferedImage bufferedImage = ImageIO.read(new File(path));
// 调用方法
QRCodeDecoder codeDecoder = new QRCodeDecoder();
result = new String(codeDecoder.decode(new MyQRCodeImage(
bufferedImage)), "utf-8");
System.out.println("二维码的内容为:" + result);
} catch (DecodingFailedException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.awt.image.BufferedImage;
import jp.sourceforge.qrcode.data.QRCodeImage;
public class MyQRCodeImage implements QRCodeImage {
BufferedImage bufferedImage;
public MyQRCodeImage(BufferedImage bufferedImage) {
this.bufferedImage=bufferedImage;
}
public int getHeight() {
return bufferedImage.getHeight();
}
public int getPixel(int x, int y) {
return bufferedImage.getRGB(x, y);
}
public int getWidth() {
return bufferedImage.getWidth();
}
}
生成的二维码如下:
[项目的源码地址:]
(http://pan.baidu.com/s/1i5cG7Gh)