以下位置可以下載zxing(Code License:Apache License 2.0):
http://code.google.com/p/zxing/downloads/list
我下載的是Zxing-1.7.zip
1、安裝JDK
2、編譯ZXing
可以參照Google的手冊進行編譯
http://code.google.com/p/zxing/wiki/GettingStarted
3、找到編譯好的core.jar和javase.jar備用
(這兩個文件主要用於PC開發,如果需要在Android上開發的話,需要編譯相應的Source)
4、測試QRcode的生成和解碼
package com.dalian.qrcode.test; import java.awt.image.BufferedImage; import java.io.File; import java.util.Hashtable; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.MultiFormatWriter; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.DecodeHintType; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.HybridBinarizer; public class QRcoder { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub encode(); decode(); } static void encode(){ try{ //String str = "http://www.cnblogs.com/tompandas"; StringBuilder sb = new StringBuilder(1024); sb.append("Name:TomPandas"); sb.append("\r\n"); sb.append("WebSite:http://www.cnblogs.com/tompandas"); sb.append("\r\n"); String str = sb.toString(); String picFormat = "png"; String path = "d:/test_qrcode"; File file = new File(path + "." + picFormat); str = new String(str.getBytes("GBK"), "ISO-8859-1"); Hashtable hints = new Hashtable(); BitMatrix bitMatrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, 200, 200, hints); MatrixToImageWriter.writeToFile(bitMatrix, picFormat, file); }catch(Exception ex){ System.out.println(ex.toString()); } } static void decode(){ try{ String file = "d:/test_qrcode.png"; Result result = null; BufferedImage image = null; image = ImageIO.read(new File(file)); LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Hashtable<Object, Object> hints = new Hashtable<Object, Object>(); hints.put(DecodeHintType.CHARACTER_SET, "GBK"); result = new MultiFormatReader().decode(bitmap, hints); String rtn = result.getText(); System.out.println(rtn); }catch(Exception ex){ System.out.println(ex.toString()); } } }
以下是生成的文件
如果中文有亂碼的話,請參照以下試試,反正我沒試過。
源代碼中有兩處UTF-8的問題,會導致亂碼,
其一:com.google.zxing.qrcode.encoder.encoder類中的
internal const System.String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1";
此處,將ISO-8859-1改為UTF-8
其二:com.google.zxing.qrcode.decoder.DecodedBitStreamParser類的成員
private const System.String UTF8 = "UTF8";
應將UTF8改為UTF-8