1. 程式人生 > >java解析二維碼

java解析二維碼

package main;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

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.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
 
/**
 * 二維碼解碼功能
 */
public class ZxingDecode {
	
    /**
     * 二維碼解碼
     * @param filePath
     * @return
     */
    public static String decode(String filePath) {
        return decode(new File(filePath));
    }
 
    /**
     * 二維碼解碼
     * @param file
     * @return
     */
    public static String decode(File file) {
        BufferedImage image;
        try {
            image = ImageIO.read(file);
 
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            //解碼設定編碼方式為:UTF-8
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            //優化精度
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            //複雜模式,開啟PURE_BARCODE模式
            hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 對影象進行解碼
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static void main(String[] args) {
    	System.out.println(ZxingDecode.decode("D:/qr/二維碼.png"));
	}
 
}