我目前正在尝试制作一个脚本,用于在目录和子目录中查找扩展名为 *.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/