Find images with certain extensions recursively

佐手、 提交于 2021-02-18 22:33:11

问题


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.

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);

回答1:


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";
}
?>


来源:https://stackoverflow.com/questions/24980967/find-images-with-certain-extensions-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!