java识别图片二维码及提高识别率-ZXING

本文档内容主要基于java,包含图片中二维码的识别,以及如何提高识别精度

准备工作

引入jar包

        
        
            com.google.zxing
            javase
            3.5.1
        
        
        
            com.beust
            jcommander
            1.82
        
        
        
            com.google.zxing
            core
            3.5.1
        

代码介绍

简单识别

本代码可用于普通且不包含中文内容的二维码图片的识别

    public static String readQrCodeImage(FileInputStream fileInputStream) throws Exception {
        BufferedImage readImage = ImageIO.read(fileInputStream);
        LuminanceSource source = new BufferedImageLuminanceSource(readImage);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result decode = qrCodeReader.decode(bitmap);
        return decode.getText();
    }

包含中文情况识别

本代码可用于包含中文内容的二维码图片的识别

    public static String readQrCodeImage(FileInputStream fileInputStream) throws Exception {
        BufferedImage readImage = ImageIO.read(fileInputStream);
        LuminanceSource source = new BufferedImageLuminanceSource(readImage);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        EnumMap hints = new EnumMap<>(DecodeHintType.class);
        //设置中文编码
        hints.put(DecodeHintType.CHARACTER_SET,"GBK");
        Result decode = qrCodeReader.decode(bitmap,hints);
        return decode.getText();
    }

图片清晰度差情况识别

本代码可用于图片清晰度差,图片中二维码不清晰情况下二维码图片的识别
针对图片不清晰情况,又不同措施:
1.对图片进行去除噪点的操作,生成高质量的图片(代价较大)
2.对图片进行截取,降低识别图片大小,提高图片中二维码所占比例
本次采用第2种方式对图片进行处理

    public static String readQrCodeImage(FileInputStream fileInputStream) throws Exception {
        BufferedImage readImage = ImageIO.read(fileInputStream);
        int width = readImage.getWidth();
        int height = readImage.getHeight();
        //截取图片左下1/4进行识别
        readImage = readImage.getSubimage(0, height/2, width/2 , height/2);
        LuminanceSource source = new BufferedImageLuminanceSource(readImage);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        EnumMap hints = new EnumMap<>(DecodeHintType.class);
        hints.put(DecodeHintType.CHARACTER_SET,"GBK");
        Result decode = qrCodeReader.decode(bitmap,hints);
        return decode.getText();
    }

你可能感兴趣的:(java识别图片二维码及提高识别率-ZXING)