从目录中提取图像-PHP


Pull Images from directory - PHP

我试图简单地从我的目录/img中提取图像,并以以下方式将它们动态加载到网站中。

            <img src="plates/photo1.jpg">

就是这样。它看起来很简单,但我找到的所有代码基本上都不起作用。

我正在努力实现的目标是:

   <?php
   $a=array();
   if ($handle = opendir('plates')) {
while (false !== ($file = readdir($handle))) {
   if(preg_match("/'.png$/", $file)) 
        $a[]=$file;
else if(preg_match("/'.jpg$/", $file)) 
        $a[]=$file;
else if(preg_match("/'.jpeg$/", $file)) 
        $a[]=$file;
}
closedir($handle);
   }
 foreach($a as $i){
echo "<img src='".$i."' />";
 }
 ?>

这可以使用glob()非常容易地完成。

$files = glob("plates/*.{png,jpg,jpeg}", GLOB_BRACE);
foreach ($files as $file)
    print "<img src='"plates/$file'" />";

您希望您的源代码显示为plates/photo1.jpg,但当您执行echo "<img src='".$i."' />";时,您只写文件名。尝试将其更改为:

<?php
$a = array();
$dir = 'plates';
if ($handle = opendir($dir)) {
  while (false !== ($file = readdir($handle))) {
    if (preg_match("/'.png$/", $file)) $a[] = $file;
    elseif (preg_match("/'.jpg$/", $file)) $a[] = $file;
    elseif (preg_match("/'.jpeg$/", $file)) $a[] = $file;
  }
  closedir($handle);
}
foreach ($a as $i) {
  echo "<img src='" . $dir . '/' . $i . "' />";
}
?>

您应该使用Glob而不是opendir/closedir。它要简单得多。

我不太确定你想做什么,但你这可能会让你走上正确的轨道

<?php
foreach (glob("/plates/*") as $filename) {
    $path_parts = pathinfo($filename);
    if($path_parts['extension'] == "png") {
        // do something
    } elseif($path_parts['extension'] == "jpg") {
        // do something else
    }
}
?>