java解析二维码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xuxile/article/details/81779770
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"));
	}
 
}

猜你喜欢

转载自blog.csdn.net/xuxile/article/details/81779770
今日推荐