如何檢測圖片中是否含有二維碼


1、首先在IDEA中創建一個普通的Maven項目。



ok我們已經成功創建一個Maven項目!

2、向pom.xml中導入依賴。


maven倉庫:https://mvnrepository.com/

進入maven倉庫之后搜索:yzk18:

選擇一個最新的版本:

然后將下面的maven依賴坐標copy到pom.xml文件中。

<!-- https://mvnrepository.com/artifact/com.yzk18/yzk18-commons -->
<dependency>
    <groupId>com.yzk18</groupId>
    <artifactId>yzk18-commons</artifactId>
    <version>1.5</version>
</dependency>

然后我們准備在一個文件夾里放入幾張帶二維碼的圖片和不帶二維碼的圖片。

3、helloworld

分析:

  • 首先掃描一個文件夾下的所有圖片文件;
  • 然后查看是否存在帶二維碼的圖片,如果有的話就輸出"有宣傳性二維碼圖片",否則就提示"檢測通過"。

(1)獲取圖片文件並打印出來。

import com.yzk18.commons.IOHelpers;

import java.util.Arrays;

public class QRCodeFound {
    public static void main(String[] args) {
        // 1、遞歸掃描一個文件夾下的所有圖片文件
        String[] files = IOHelpers.getFilesRecursively("D:\\temp\\test1", "png", "jpg", "gif");
        System.out.println(Arrays.toString(files));

        //2、通過增強for遍歷每一個文件
        for (String file:files){
            System.out.println(file);
        }
    }
}

(2)檢查圖片中是否含有二維碼。

import com.google.zxing.Result;
import com.yzk18.commons.IOHelpers;
import com.yzk18.commons.QRCodeHelpers;

import java.util.Arrays;

public class QRCodeFound {
    public static void main(String[] args) {
        // 1、遞歸掃描一個文件夾下的所有圖片文件
        String[] files = IOHelpers.getFilesRecursively("D:\\temp\\test1", "png", "jpg", "gif");
        System.out.println(Arrays.toString(files));

        //2、通過增強for遍歷每一個文件
        for (String file : files) {
            //System.out.println(file);
            // 3、經過試驗猜測發現:如果圖片中不含有二維碼,則返回值為null
            Result result = QRCodeHelpers.parseImage(file);
            if (result != null) {
                System.out.println("有宣傳性二維碼圖片");
            }

        }
    }
}

(3)完善:如果發現有二維碼的圖片出現就不讓它放行吧😂。

ok我們把那兩張帶有二維碼的圖片刪掉,然后再運行代碼:

import com.google.zxing.Result;
import com.yzk18.commons.IOHelpers;
import com.yzk18.commons.QRCodeHelpers;

import java.util.Arrays;

public class QRCodeFound {
    public static void main(String[] args) {
        // 1、掃描一個文件夾下的所有圖片文件
        String[] files = IOHelpers.getFilesRecursively("D:\\temp\\test1", "png", "jpg", "gif");
        System.out.println(Arrays.toString(files));

        //是否找到二維碼
        boolean qrcodeFound = false;

        //2、通過增強for遍歷每一個文件
        for (String file : files) {
            //System.out.println(file);
            // 3、經過試驗猜測發現:如果圖片中不含有二維碼,則返回值為null
            Result result = QRCodeHelpers.parseImage(file);
            if (result != null) {
                qrcodeFound = true;
                break;
            }
        }
        if (qrcodeFound) {
            System.out.println("有宣傳性二維碼圖片");
        } else {
            System.out.println("檢測通過");
        }

    }
}

總結:

  • 學會閱讀文檔、學會"Trial and Error"才會使我們真正的長大😆。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM