package com.laning.qrcode;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
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.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
public class ReaderQRCode {
public static void main(String[] args) {
File dstqrcode = new File("E:/大一课程/java编程/JAVA生成二维码jar包/2.png");
try {
readQRCode(dstqrcode);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 1 读取图片
* 2转化为亮度数据源
* 3使用转换器把亮度数据源转换为二进制位数
* 4再把二进制位数据在换为二进制位图
* 5读取内容
* @throws IOException
* @throws NotFoundException
*/
//读取二维码的工具方法
private static void readQRCode(File dstqrcode) throws IOException, NotFoundException{
//1 读取图片
BufferedImage img = ImageIO.read(dstqrcode);
//2转化为亮度数据源 LuminanceSource有四个实现类,可以去官网查
LuminanceSource luminnanceSource = new BufferedImageLuminanceSource(img);
//3使用转换器把亮度数据源转换为二进制位数
Binarizer binarizer = new HybridBinarizer(luminnanceSource);
//4再把二进制位数据在换为二进制位图
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
//5读取内容
MultiFormatReader formatReader = new MultiFormatReader();
HashMap<DecodeHintType,Object> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET,"utf-8");
Result decode = formatReader.decode(binaryBitmap, hints);
System.out.println(decode.getText());
}
}