递归查找具有某些扩展名的图像 [英] Find images with certain extensions recursively

查看:36
本文介绍了递归查找具有某些扩展名的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试创建一个脚本,以在目录和子目录中查找带有* .jpg/* .png扩展名的图像.

I am currently trying to make a script that will find images with *.jpg / *.png extensions in directories and subdirectories.

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

If some picture with one of these extensions is found, then save it to an array with path, name, size, height and width.

到目前为止,我有这段代码,可以找到所有文件,但是我不知道如何仅获取jpg/png图像.

So far I have this piece of code, which will find all files, but I don't know how to get only jpg / png images.

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 

} 
}

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

I call this function in my template like this

ImageCheck::getDirectory($dir);

推荐答案

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

Save a lot of headache and just use PHP's built in recursive search with a regex expression:

<?php

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

?>

如果您不熟悉使用对象,请按以下步骤迭代响应:

In case you are not familiar with working with objects, here is how to iterate the response:

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

这篇关于递归查找具有某些扩展名的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆