递归查找具有某些扩展名的图像

编程入门 行业动态 更新时间:2024-10-26 22:28:12
本文介绍了递归查找具有某些扩展名的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在尝试创建一个脚本,以在目录和子目录中查找带有* .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( '&nbsp;', ( $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"; } ?>

更多推荐

递归查找具有某些扩展名的图像

本文发布于:2023-11-02 17:56:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1553041.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   扩展名   图像

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!