二维码项目ZXing在Java中的使用

项目地址:

http://code.google.com/p/zxing/

可以先到这个地址下载Zxing的支持类库

ZXing是一个开源Java类库用于解析多种格式的1D/2D条形码。目标是能够对QR编码、Data Matrix、UPC的1D条形码进行解码。 其提供了多种平台下的客户端包括:J2ME、J2SE和Android。

下载介绍下ZXing在Java中的使用:

 

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.Result;
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.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
/**
 * 二维码学习
 * @author LiYongqiang
 */
public class ZxingTest {
	public static void main(String[] args) throws Exception{
		String content = "http://192.168.0.1:8080/sfda/";
		content = new String(content.getBytes("GBK"),"iso-8859-1");
		String imagePath = "c:\\code.png";
		File file = new File(imagePath);
		
		QRCodeWriter writer = new QRCodeWriter();
		try {
			//生成二维码
			BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE,200, 200);
			MatrixToImageWriter.writeToFile(matrix, "png", file);
			//读取二维码
			QRCodeReader reader = new QRCodeReader();
			BufferedImage image = ImageIO.read(file);
			LuminanceSource source = new BufferedImageLuminanceSource(image );
			Binarizer binarizer = new HybridBinarizer(source );
			BinaryBitmap imageBinaryBitmap = new BinaryBitmap(binarizer  );
			Result result = reader.decode(imageBinaryBitmap);
			System.out.println("result = "+ result.toString());
            System.out.println("resultFormat = "+ result.getBarcodeFormat());
            System.out.println("resultText = "+ result.getText());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

你可能感兴趣的:(zxing)