0

我在下面有我的代码。它在2个目录中搜索图像,如果找到图像,它将打印图像,如果找不到则不显示图像。

<?php
$file = 'testimage.png'; 

$dir = 
   [$_SERVER['DOCUMENT_ROOT'] . "/pathA/", 
    $_SERVER['DOCUMENT_ROOT'] . "/pathB/"];

foreach( $dir as $d )
{

    if( file_exists( $d . $file )) 
    {
        $image = $d . $file;    
    }

}

if(empty($image))
{
    $image = null;
}

$img = imagecreatefrompng($image);

header("Content-type: image/png");
imagePng($img);
?>

有人可以为我提供上述代码的增强或方便的方式吗?

4

2 回答 2

1

您可以设置 $image = null; 作为默认设置,因此您不必检查 empty($image) 并且可以在循环中添加一个中断,因此如果您已经在第一个路径中找到它,则不必总是查看两个路径:

 $image = null;
 foreach( $dir as $d )
 {

    if( file_exists( $d . $file )) 
    {
        $image = $d . $file;    
        break; //Exit loop when the file is found
    }

 } 
 //Remove empty($image)-Check

你不能真正简化检查,因为在某种程度上你必须使用像“file_exists”这样的函数,如果文件存在则返回。如果您有不同的路径,您还必须检查直到找到它(或者它不存在)

所以:你的代码很好。

于 2013-10-25T06:17:24.260 回答
0

做这些事情的一种更方便的方法是使用第三方库。如果您对此感到满意,您可以查看Nette FinderSymfony Finder(或任何其他类似的库)。

使用 Nette Finder,示例可能如下所示:

$images = iterator_to_array(Finder::findFiles($file)->in($dir));
$image = $images ? reset($images) : NULL;

$img = imagecreatefrompng($image->getPath());
// ...

如果您只有这个脚本处理文件,那可能是一种矫枉过正。但是,如果您更多地使用文件,那么绝对值得一试。

于 2013-10-25T06:09:52.717 回答