php - 递归查找具有特定扩展名的图像

标签 php image recursion

我目前正在尝试制作一个脚本,用于在目录和子目录中查找扩展名为 *.jpg/*.png 的图像。

如果找到具有这些扩展名之一的图片,则将其保存到包含路径、名称、大小、高度和宽度的数组中。

到目前为止我有这段代码,它将找到所有文件,但我不知道如何只获取 jpg/png 图像。

class ImageCheck {

public static function getDirectory( $path = '.', $level = 0 ){ 

    $ignore = array( 'cgi-bin', '.', '..' ); 
    // Directories to ignore when listing output.

    $dh = @opendir( $path ); 
    // Open the directory to the handle $dh 

    while( false !== ( $file = readdir( $dh ) ) ){ 
    // Loop through the directory 

        if( !in_array( $file, $ignore ) ){ 
        // Check that this file is not to be ignored 

            $spaces = str_repeat( ' ', ( $level * 4 ) ); 
            // Just to add spacing to the list, to better 
            // show the directory tree. 

            if( is_dir( "$path/$file" ) ){ 
            // Its a directory, so we need to keep reading down... 

                echo "<strong>$spaces $file</strong><br />"; 
                ImageCheck::getDirectory( "$path/$file", ($level+1) ); 
                // Re-call this same function but on a new directory. 
                // this is what makes function recursive.  

            } else { 

                echo "$spaces $file<br />"; 
                // Just print out the filename 

            } 

        } 

    } 

    closedir( $dh ); 
    // Close the directory handle 

} 
}

我在我的模板中这样调用这个函数

ImageCheck::getDirectory($dir);

最佳答案

省去了很多麻烦,只需使用 PHP 的内置递归搜索和正则表达式:

<?php

$Directory = new RecursiveDirectoryIterator('path/to/project/');
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator, '/^.+(.jpe?g|.png)$/i', RecursiveRegexIterator::GET_MATCH);

?>

如果您不熟悉使用对象,这里是迭代响应的方法:

<?php
foreach($Regex as $name => $Regex){
    echo "$name\n";
}
?>

关于php - 递归查找具有特定扩展名的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24980967/

相关文章:

php - 从 jQuery UI 对话框进行 AJAX 调用

php - 来自 MySQL JSON 编码数组的 Google 图表

python - 一般如何将递归程序转换为迭代程序?

algorithm - 了解归并排序算法

php - 深度递归内存泄漏 - 取消设置 fopen 资源?

php - fatal error : Uncaught CurlException: 26: failed creating formpost data thrown

jquery - 我需要固定宽度容器中的图形和图像来跨越浏览器窗口的整个宽度

jquery - 检查 jquery(js) 中的字段是否为空?

python - Tensorflow:仅在需要时将图像加载到内存中

c# - 类型 'TNestedInterface' 必须可转换为 'INestedInterfaceTest' 才能将其用作参数 'TNestedInterface'