使用zxing 生成和解析二維碼

package cn.wyj;

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 test
{

	/**
	 * @param args
	 * @throws WriterException 
	 * @throws IOException 
	 */
	public static void main(String[] args) throws WriterException, IOException
	{
		String text = "你們好好學習";
		int width = 200;
		int height = 200;
		String format = "png";
		Hashtable hints = new Hashtable();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height,hints);  
		File outputFile = new File("d:\\new.bmp");
		MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
	}

}
package cn.wyj;

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.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

public class Test2
{
	public static void main(String[] args)
	{
         String imgPath = "D:\\new.bmp";  
         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());  
         }  

	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章