文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

java实现识别二维码图片功能方法详解与实例源码

2022-12-10 12:00

关注

首先添加依赖

<dependency>
     <groupId>com.google.zxing</groupId>
     <artifactId>javase</artifactId>
     <version>3.2.1</version>
</dependency>
<dependency>
     <groupId>com.google.zxing</groupId>
     <artifactId>core</artifactId>
     <version>3.3.3</version>
</dependency>

java识别二维码代码实现

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import sun.misc.BASE64Decoder;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QRCodeUtils {
     
     public static String deEncodeByPath(String path) {
     String content = null;
     BufferedImage image;
     try {
         image = ImageIO.read(new File(path));
         LuminanceSource source = new BufferedImageLuminanceSource(image);
         Binarizer binarizer = new HybridBinarizer(source);
         BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
         Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
         hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
         Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
         System.out.println("图片中内容: ");
         System.out.println("content: " + result.getText());
         content = result.getText();
     } catch (IOException e) {
         e.printStackTrace();
     } catch (NotFoundException e) {
     //这里判断如果识别不了带LOGO的图片,重新添加上一个属性
         try {
     image = ImageIO.read(new File(path));
     LuminanceSource source = new BufferedImageLuminanceSource(image);
     Binarizer binarizer = new HybridBinarizer(source);
     BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
     Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
     //设置编码格式
     hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
     //设置优化精度
     hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
     //设置复杂模式开启(我使用这种方式就可以识别微信的二维码了)
     hints.put(DecodeHintType.PURE_BARCODE,Boolean.TYPE);
     Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
     System.out.println("图片中内容: ");
     System.out.println("content: " + result.getText());
     content = result.getText();
     } catch (IOException e) {
     e.printStackTrace();
     } catch (NotFoundException e) {
     e.printStackTrace();
     }
     }
     return content;
     }
}

测试:

public static void main(String [] args){
     deEncodeByPath("D:\\Users/admin/Desktop/erweima/timg (5).jpg");//二维码图片路径
}

Java二维码图片调优

如果上述不能识别的话,那么就需要对图片处理一次,然后再进行识别,这里是个调优图片的工具类。

package com.face.ele.common.utils;
 
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
 

public class ImageOptimizationUtil {
 
     // 阈值0-255
     public static int YZ = 150;
 
     
     public static void binarization(String filePath, String fileOutputPath) throws IOException {
     File file = new File(filePath);
     BufferedImage bi = ImageIO.read(file);
     // 获取当前图片的高,宽,ARGB
     int h = bi.getHeight();
     int w = bi.getWidth();
     int arr[][] = new int[w][h];
 
     // 获取图片每一像素点的灰度值
     for (int i = 0; i < w; i++) {
         for (int j = 0; j < h; j++) {
         // getRGB()返回默认的RGB颜色模型(十进制)
         arr[i][j] = getImageGray(bi.getRGB(i, j));// 该点的灰度值
         }
     }
 
     // 构造一个类型为预定义图像类型,BufferedImage
     BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_BINARY);
 
     // 和预先设置的阈值大小进行比较,大的就显示为255即白色,小的就显示为0即黑色
     for (int i = 0; i < w; i++) {
         for (int j = 0; j < h; j++) {
         if (getGray(arr, i, j, w, h) > YZ) {
             int white = new Color(255, 255, 255).getRGB();
             bufferedImage.setRGB(i, j, white);
         } else {
             int black = new Color(0, 0, 0).getRGB();
             bufferedImage.setRGB(i, j, black);
         }
         }
 
     }
     ImageIO.write(bufferedImage, "jpg", new File(fileOutputPath));
     }
 
     
     private static int getImageGray(int rgb) {
     String argb = Integer.toHexString(rgb);// 将十进制的颜色值转为十六进制
     // argb分别代表透明,红,绿,蓝 分别占16进制2位
     int r = Integer.parseInt(argb.substring(2, 4), 16);// 后面参数为使用进制
     int g = Integer.parseInt(argb.substring(4, 6), 16);
     int b = Integer.parseInt(argb.substring(6, 8), 16);
     int gray = (int) (r*0.28 + g*0.95 + b*0.11);
     return gray;
     }
 
     
     public static int getGray(int gray[][], int x, int y, int w, int h) {
     int rs = gray[x][y] + (x == 0 ? 255 : gray[x - 1][y]) + (x == 0 || y == 0 ? 255 : gray[x - 1][y - 1])
         + (x == 0 || y == h - 1 ? 255 : gray[x - 1][y + 1]) + (y == 0 ? 255 : gray[x][y - 1])
         + (y == h - 1 ? 255 : gray[x][y + 1]) + (x == w - 1 ? 255 : gray[x + 1][y])
         + (x == w - 1 || y == 0 ? 255 : gray[x + 1][y - 1])
         + (x == w - 1 || y == h - 1 ? 255 : gray[x + 1][y + 1]);
     return rs / 9;
     }
 
     
     public static void opening(String filePath, String fileOutputPath) throws IOException {
     File file = new File(filePath);
     BufferedImage bi = ImageIO.read(file);
     // 获取当前图片的高,宽,ARGB
     int h = bi.getHeight();
     int w = bi.getWidth();
     int arr[][] = new int[w][h];
     // 获取图片每一像素点的灰度值
     for (int i = 0; i < w; i++) {
         for (int j = 0; j < h; j++) {
         // getRGB()返回默认的RGB颜色模型(十进制)
         arr[i][j] = getImageGray(bi.getRGB(i, j));// 该点的灰度值
         }
     }
 
     int black = new Color(0, 0, 0).getRGB();
     int white = new Color(255, 255, 255).getRGB();
     BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_BINARY);
     // 临时存储腐蚀后的各个点的亮度
     int temp[][] = new int[w][h];
     // 1.先进行腐蚀操作
     for (int i = 0; i < w; i++) {
         for (int j = 0; j < h; j++) {
         
         if (getGray(arr, i, j, w, h) < 30) {
             temp[i][j] = 0;
         } else{
             temp[i][j] = 255;
         }
         }
     }
 
     // 2.再进行膨胀操作
     for (int i = 0; i < w; i++) {
         for (int j = 0; j < h; j++) {
         bufferedImage.setRGB(i, j, white);
         }
     }
     for (int i = 0; i < w; i++) {
         for (int j = 0; j < h; j++) {
         // 为0表示改点和周围8个点都是黑,则该点腐蚀操作后为黑
         if (temp[i][j] == 0) {
             bufferedImage.setRGB(i, j, black);
             if(i > 0) {
             bufferedImage.setRGB(i-1, j, black);
             }
             if (j > 0) {
             bufferedImage.setRGB(i, j-1, black);
             }
             if (i > 0 && j > 0) {
             bufferedImage.setRGB(i-1, j-1, black);
             }
             if (j < h-1) {
             bufferedImage.setRGB(i, j+1, black);
             }
             if (i < w-1) {
             bufferedImage.setRGB(i+1, j, black);
             }
             if (i < w-1 && j > 0) {
             bufferedImage.setRGB(i+1, j-1, black);
             }
             if (i < w-1 && j < h-1) {
             bufferedImage.setRGB(i+1, j+1, black);
             }
             if (i > 0 && j < h-1) {
             bufferedImage.setRGB(i-1, j+1, black);
             }
         }
         }
     }
 
     ImageIO.write(bufferedImage, "jpg", new File(fileOutputPath));
     }
 
     public static void main(String[] args) {
     String fullPath="E:\\weijianxing\\img\\微信图片_20201202160240.jpg";
     String newPath="E:\\weijianxing\\img\\1new_微信图片_20201202160240.jpg";
     try {
         ImageOptimizationUtil.binarization(fullPath,newPath);
     } catch (IOException e) {
         e.printStackTrace();
     }
     }
}

可以手动测试,然后对改代码的部分进行调正对应的参数-- gray变量里的计算进行灰度调整

private static int getImageGray(int rgb) {
     String argb = Integer.toHexString(rgb);// 将十进制的颜色值转为十六进制
     // argb分别代表透明,红,绿,蓝 分别占16进制2位
     int r = Integer.parseInt(argb.substring(2, 4), 16);// 后面参数为使用进制
     int g = Integer.parseInt(argb.substring(4, 6), 16);
     int b = Integer.parseInt(argb.substring(6, 8), 16);
     int gray = (int) (r*0.28 + g*0.95 + b*0.11);
     return gray;
     }

第二种方法:

package com.ghl.magicbox.qrcode.b;
import cn.hutool.core.util.IdUtil;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.CLAHE;
import org.opencv.imgproc.Imgproc;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class QRCodeUtil {
    
    private final static int TIMES = 4;
    static {
        // 加载Opencv的dll文件
        URL url = ClassLoader.getSystemResource("lib/opencv_java3416.dll");
        System.load(url.getPath());
    }
    
    public static String complexDecode(File file) {
        String tempFilePath = null;
        try {
            log.debug("QRCodeUtil -> complexDecode() fileName:{}",file.getName());
            tempFilePath = getFilePath(file.getName());
            //第一次解析:直接解析
            log.debug("QRCodeUtil -> complexDecode() firstDecode begin by:{}",file.getName());
            String codeDataByFirst = simpleDecode(file);
            if (codeDataByFirst != null) {
                return codeDataByFirst;
            }
            //第二次解析:定位图中二维码,截图放大
            log.debug("QRCodeUtil -> complexDecode() secondDecode begin by:{}",file.getName());
            piz(file.getAbsolutePath(),tempFilePath);
            String codeDataBySecond = simpleDecode(tempFilePath);
            if (codeDataBySecond != null) {
                return codeDataBySecond;
            }
            //第三次解析:将截图后二维码二值化
            log.debug("QRCodeUtil -> complexDecode() thirdDecode begin by:{}",file.getName());
            Mat mat = binarization(tempFilePath);
            String codeDataByThird = simpleDecode(tempFilePath);
            if (codeDataByThird != null) {
                return codeDataByThird;
            }
            //第四次解析: 进行限制对比度的自适应直方图均衡化处理
            log.debug("QRCodeUtil -> complexDecode() fourthDecode begin by:{}",file.getName());
            limitContrast(tempFilePath,mat);
            String codeDataByFourth = simpleDecode(tempFilePath);
            if (codeDataByFourth != null) {
                log.debug("QRCodeUtil -> complexDecode() fileName:{} state:{} result:{}",file.getName(),Boolean.TRUE,codeDataByFourth);
                return codeDataByFourth;
            }
            log.debug("QRCodeUtil -> complexDecode() fileName:{} state:{}",file.getName(), Boolean.FALSE);
        } finally {
            file.deleteOnExit();
            if (tempFilePath != null){
                file = new File(tempFilePath);
                file.deleteOnExit();
            }
        }
        return null;
    }
    
    public static String complexDecode(String path) {
        return complexDecode(new File(path));
    }
    
    public static String complexDecode(MultipartFile originalFile) {
        String filePath = getFilePath(originalFile.getOriginalFilename());
        File mkFile = new File(filePath);
        if (!mkFile.exists()){
            mkFile.mkdir();
            log.debug("QRCodeUtil -> complexDecode() create temp file ready by:{}",originalFile.getOriginalFilename());
        }
        try {
            originalFile.transferTo(mkFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return complexDecode(mkFile);
    }
    
    public static String simpleDecode(String path) {
        return simpleDecode(new File(path));
    }
    
    public static String simpleDecode(File file) {
        try {
            BufferedImage 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>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);
            return result.getText();
        } catch (Exception e) {
            return null;
        }
    }
    
    @SneakyThrows
    private static String getFilePath(String fileName) {
        String path = ResourceUtils.getFile("classpath:").getPath() + "/static/decodeWork/";
        File folder = new File(path);
        if (!folder.exists()){
            folder.mkdirs();
        }
        String contentType = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1) : null;
        String newFileName = IdUtil.getSnowflake(0, 0).nextId() + "." + contentType;
        return path + newFileName;
    }
    
    private static void piz(String filePath, String tempFilePath) {
        Mat srcGray = new Mat();
        Mat src = Imgcodecs.imread(filePath, 1);
        List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
        List<MatOfPoint> markContours = new ArrayList<MatOfPoint>();
        //System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
//        URL url = ClassLoader.getSystemResource("lib/opencv_java3416.dll");
//        System.load(url.getPath());
        //图片太小就放大
        if (src.width() * src.height() < 90000) {
            Imgproc.resize(src, src, new Size(800, 600));
        }
        // 彩色图转灰度图
        Imgproc.cvtColor(src, srcGray, Imgproc.COLOR_RGB2GRAY);
        // 对图像进行平滑处理
        Imgproc.GaussianBlur(srcGray, srcGray, new Size(3, 3), 0);
        Imgproc.Canny(srcGray, srcGray, 112, 255);
        Mat hierarchy = new Mat();
        Imgproc.findContours(srcGray, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_NONE);
        for (int i = 0; i < contours.size(); i++) {
            MatOfPoint2f newMtx = new MatOfPoint2f(contours.get(i).toArray());
            RotatedRect rotRect = Imgproc.minAreaRect(newMtx);
            double w = rotRect.size.width;
            double h = rotRect.size.height;
            double rate = Math.max(w, h) / Math.min(w, h);
            // 长短轴比小于1.3,总面积大于60
            if (rate < 1.3 && w < srcGray.cols() / 4 && h < srcGray.rows() / 4 && Imgproc.contourArea(contours.get(i)) > 60) {
                // 计算层数,二维码角框有五层轮廓(有说六层),这里不计自己这一层,有4个以上子轮廓则标记这一点
                double[] ds = hierarchy.get(0, i);
                if (ds != null && ds.length > 3) {
                    int count = 0;
                    if (ds[3] == -1) {
                        //最外层轮廓排除
                        continue;
                    }
                    // 计算所有子轮廓数量
                    while ((int) ds[2] != -1) {
                        ++count;
                        ds = hierarchy.get(0, (int) ds[2]);
                    }
                    if (count >= 4) {
                        markContours.add(contours.get(i));
                    }
                }
            }
        }
        
        if (markContours.size() == 0) {
            return;
        } else if (markContours.size() == 1) {
            capture(markContours.get(0), src ,tempFilePath);
        } else {
            List<MatOfPoint> threePointList = new ArrayList<>();
            threePointList.add(markContours.get(0));
            threePointList.add(markContours.get(1));
            capture(threePointList, src,tempFilePath);
        }
    }
    
    private static void capture(List<MatOfPoint> threePointList, Mat src, String tempFilePath) {
        Point p1 = centerCal(threePointList.get(0));
        Point p2 = centerCal(threePointList.get(1));
        Point centerPoint = new Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);
        double width = Math.abs(p1.x - p2.x) + Math.abs(p1.y - p2.y) + 50;
        // 设置截取规则
        Rect roiArea = new Rect((int) (centerPoint.x - width) > 0 ? (int) (centerPoint.x - width) : 0,
                (int) (centerPoint.y - width) > 0 ? (int) (centerPoint.y - width) : 0, (int) (2 * width),
                (int) (2 * width));
        // 截取二维码
        Mat dstRoi = new Mat(src, roiArea);
        // 放大图片
        Imgproc.resize(dstRoi, dstRoi, new Size(TIMES * width, TIMES * width));
        Imgcodecs.imwrite(tempFilePath, dstRoi);
    }
    
    private static void capture(MatOfPoint matOfPoint, Mat src, String tempFilePath) {
        Point centerPoint = centerCal(matOfPoint);
        int width = 200;
        Rect roiArea = new Rect((int) (centerPoint.x - width) > 0 ? (int) (centerPoint.x - width) : 0,
                (int) (centerPoint.y - width) > 0 ? (int) (centerPoint.y - width) : 0, (int) (2 * width),
                (int) (2 * width));
        // 截取二维码
        Mat dstRoi = new Mat(src, roiArea);
        // 放大图片
        Imgproc.resize(dstRoi, dstRoi, new Size(TIMES * width, TIMES * width));
        Imgcodecs.imwrite(tempFilePath, dstRoi);
    }
    
    private static Point centerCal(MatOfPoint matOfPoint) {
        double centerx = 0, centery = 0;
        MatOfPoint2f mat2f = new MatOfPoint2f(matOfPoint.toArray());
        RotatedRect rect = Imgproc.minAreaRect(mat2f);
        Point vertices[] = new Point[4];
        rect.points(vertices);
        centerx = ((vertices[0].x + vertices[1].x) / 2 + (vertices[2].x + vertices[3].x) / 2) / 2;
        centery = ((vertices[0].y + vertices[1].y) / 2 + (vertices[2].y + vertices[3].y) / 2) / 2;
        Point point = new Point(centerx, centery);
        return point;
    }
    
    private static Mat binarization(String filePath){
        Mat mat = Imgcodecs.imread(filePath, 1);
        // 彩色图转灰度图
        Imgproc.cvtColor(mat, mat, Imgproc.COLOR_RGB2GRAY);
        // 对图像进行平滑处理
        Imgproc.blur(mat, mat, new Size(3, 3));
        // 中值去噪
        Imgproc.medianBlur(mat, mat, 5);
        // 这里定义一个新的Mat对象,主要是为了保留原图,未下次处理做准备
        Mat mat2 = new Mat();
        // 根据OTSU算法进行二值化
        Imgproc.threshold(mat, mat2, 205, 255, Imgproc.THRESH_OTSU);
        // 生成二值化后的图像
        Imgcodecs.imwrite(filePath, mat2);
        return mat;
    }
    
    public static void limitContrast(String filePath,Mat mat){
        CLAHE clahe = Imgproc.createCLAHE(2, new Size(8, 8));
        clahe.apply(mat, mat);
        Imgcodecs.imwrite(filePath, mat);
    }
    public static void main(String[] args) {
        String s = complexDecode("C:\\Users\\ghl\\Desktop\\b.jpg");
        System.out.println(s);
    }
}

更多关于java实现识别二维码图片功能文章请查看下面的相关链接

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯