zXing的編碼和解碼——二維碼

package com.wondersgroup.zXing;

import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
/**
 * 編碼
 */
public class MyTestEncode {
	public static void main(String[] args) throws Exception{
		try{
			String str = "CN:男;COP:公司;ZW:職務";//二維碼內容
			String path = "K:\\二維碼\\images\\TestQRCode1.png";
			Hashtable hints = new Hashtable();
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			
			
			BitMatrix bitMatrix;
			bitMatrix = new MultiFormatWriter().encode(str,
					BarcodeFormat.QR_CODE, 200, 200,hints);
			File file = new File(path);
			MatrixToImageWriter.writeToFile(bitMatrix,"png",file);
		}catch (IOException e) {
			e.printStackTrace();
		}catch(WriterException e1){
			e1.printStackTrace();
		}
	}
}


package com.wondersgroup.zXing;


import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;


import javax.imageio.ImageIO;


import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
/**
 * 解碼
 * @author Tobbey
 *
 */
public class MyTestDecode {


	public static void main(String[] args)
		throws ReaderException,InterruptedException{
		
		Reader reader = new MultiFormatReader();
		
		String imgPath = "K:\\二維碼\\images\\TestQRCode1.png";
		File file = new File(imgPath);
		
		BufferedImage image;
		try{
			image = ImageIO.read(file);
			if(image == null){
				System.out.println("Could not decode image");
			}
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
			
			Result result;
			Hashtable hints = new Hashtable();
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
			result = new MultiFormatReader().decode(bitmap, hints);
			String resultStr = result.getText();
			System.out.println(resultStr);
		}catch (IOException ioe) {
			System.out.println(ioe.toString());
		}catch(ReaderException re){
			System.out.println(re.toString());
		}
	}
}



發佈了18 篇原創文章 · 獲贊 0 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章