我目前正在尝试创建一个脚本,以在目录和子目录中查找带有* .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"; } ?>更多推荐
递归查找具有某些扩展名的图像
发布评论