Java技术实现解析读取二维码

2019-06-15 00:00:00 技术 读取 解析

此文章接上一篇:http://www.imooc.com/article/15617
Java实现读取解析二维码图片的内容两种实现方法:
方法一:

package com.imooc;

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.BinaryBitmap;
import com.google.zxing.EncodeHintType;
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 ReadQRCode {

    public static void main(String[] args) {
        try {
            MultiFormatReader formatReader = new MultiFormatReader();
            // 二维码图片位置
            File file = new File("f:/code2/Eo.png");
            // 读取图片
            BufferedImage image = ImageIO.read(file);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));

            // 定义二维码的参数
            HashMap hints = new HashMap();
            //设置编码字符集
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            //处理读取结果
            Result result = formatReader.decode(binaryBitmap, hints);

            System.out.println("解析结果:" + result.toString());
            System.out.println("二维码格式类型:" + result.getBarcodeFormat());
            System.out.println("二维码文本内容:" + result.getText());
        } catch (NotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

方法二:

package com.imooc;

import java.awt.image.BufferedImage;

import jp.sourceforge.qrcode.data.QRCodeImage;

public class MyQRCodeImage implements QRCodeImage {
    BufferedImage bufferedImage;

    public MyQRCodeImage(BufferedImage bufferedImage){
        this.bufferedImage=bufferedImage;
    }

    @Override
    public int getHeight() {
        return bufferedImage.getHeight();
    }

    @Override
    public int getPixel(int arg0, int arg1) {
        return bufferedImage.getRGB(arg0, arg1);
    }

    @Override
    public int getWidth() {
        return bufferedImage.getWidth();
    }

}
package com.imooc;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import jp.sourceforge.qrcode.QRCodeDecoder;

public class ReadQRcode1 {

    public static void main(String[] args) throws Exception {
        //指定文件路径
        File file=new File("E:/code/qrcode.png");
        //读取验证码图片
        BufferedImage bufferedImage=ImageIO.read(file);
        //调用方法
        QRCodeDecoder codeDecoder=new QRCodeDecoder();
        String result=new String(codeDecoder.decode(new MyQRCodeImage(bufferedImage)),"gb2312");

        System.out.println("二维码的内容为:"+result);

    }

}

项目目录结构:
《Java技术实现解析读取二维码》

相关文章