繁体   English   中英

从php中的文件夹中获取所有图像

[英]get all the images from a folder in php

我正在使用 WordPress。 我有一个像mytheme/images/myimages这样的图像文件夹。

我想从文件夹myimages中检索所有图像名称

请告诉我,我怎样才能得到图像名称。

尝试这个

$directory = "mytheme/images/myimages";
$images = glob($directory . "/*.jpg");

foreach($images as $image)
{
  echo $image;
}

你可以简单地使用 PHP opendir函数来完成它。

例子:

$handle = opendir(dirname(realpath(__FILE__)).'/pictures/');
while($file = readdir($handle)){
  if($file !== '.' && $file !== '..'){
    echo '<img src="pictures/'.$file.'" border="0" />';
  }
}

当您想从文件夹中获取所有图像时,请使用glob()内置函数来帮助获取所有图像。 但是,当您得到所有​​内容时,有时需要检查所有内容是否有效,因此在这种情况下,此代码可以帮助您。 此代码还将检查它是否是图像

  $all_files = glob("mytheme/images/myimages/*.*");
  for ($i=0; $i<count($all_files); $i++)
    {
      $image_name = $all_files[$i];
      $supported_format = array('gif','jpg','jpeg','png');
      $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
      if (in_array($ext, $supported_format))
          {
            echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
          } else {
              continue;
          }
    }

如果您不想检查图像类型,那么您也可以使用此代码

 $all_files = glob("mytheme/images/myimages/*.*");
 for ($i=0; $i<count($all_files); $i++)
 {
  $image_name = $all_files[$i];
  echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
 }

了解更多信息

PHP 手册

$dir = "mytheme/images/myimages";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}
$images=preg_grep ('/\.jpg$/i', $files);

非常快,因为您只扫描所需的目录。

这个答案是针对 WordPress 的

$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );

$media_dir = $base_dir . 'yourfolder/images/';
$media_url = $hase_url . 'yourfolder/images/';

$image_paths = glob( $media_dir . '*.jpg' );
$image_names = array();
$image_urls = array();

foreach ( $image_paths as $image ) {
    $image_names[] = str_replace( $media_dir, '', $image );
    $image_urls[] = str_replace( $media_dir, $media_url, $image );
}

// --- You now have:

// $image_paths ... list of absolute file paths 
// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg

// $image_urls ... list of absolute file URLs 
// e.g. http://example.com/wp-content/uploads/yourfolder/images/sample.jpg

// $image_names ... list of filenames only
// e.g. sample.jpg

以下是一些其他设置,它们将为您提供来自子主题以外的其他地方的图像。 只需将上面代码中的前 2 行替换为您需要的版本即可:

从上传目录:

// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
$upload_path = wp_upload_dir();
$base_dir = trailingslashit( $upload_path['basedir'] );
$base_url = trailingslashit( $upload_path['baseurl'] );

从父主题

// e.g. /path/to/wordpress/wp-content/themes/parent-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_template_directory() );
$base_url = trailingslashit( get_template_directory_uri() );

从儿童主题

// e.g. /path/to/wordpress/wp-content/themes/child-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );

这是我的一些代码

$dir          = '/Images';
$ImagesA = Get_ImagesToFolder($dir);
print_r($ImagesA);

function Get_ImagesToFolder($dir){
    $ImagesArray = [];
    $file_display = [ 'jpg', 'jpeg', 'png', 'gif' ];

    if (file_exists($dir) == false) {
        return ["Directory \'', $dir, '\' not found!"];
    } 
    else {
        $dir_contents = scandir($dir);
        foreach ($dir_contents as $file) {
            $file_type = pathinfo($file, PATHINFO_EXTENSION);
            if (in_array($file_type, $file_display) == true) {
                $ImagesArray[] = $file;
            }
        }
        return $ImagesArray;
    }
}
//path to the directory to search/scan
        $directory = "";
         //echo "$directory"
        //get all files in a directory. If any specific extension needed just have to put the .extension
        //$local = glob($directory . "*"); 
        $local = glob("" . $directory . "{*.jpg,*.gif,*.png}", GLOB_BRACE);
        //print each file name
        echo "<ul>";

        foreach($local as $item)
        {
        echo '<li><a href="'.$item.'">'.$item.'</a></li>';
        }

        echo "</ul>";

检查是否存在,将所有文件放入数组中,preg grep 所有 JPG 文件,回显新数组对于所有图像可以试试这个:

$images=preg_grep('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $files);


if ($handle = opendir('/path/to/folder')) {

    while (false !== ($entry = readdir($handle))) {
        $files[] = $entry;
    }
    $images=preg_grep('/\.jpg$/i', $files);

    foreach($images as $image)
    {
    echo $image;
    }
    closedir($handle);
}
    <?php
   $galleryDir = 'gallery/';
   foreach(glob("$galleryDir{*.jpg,*.gif,*.png,*.tif,*.jpeg}", GLOB_BRACE) as $photo)
   {echo "<a  href=\"$photo\">\n" ;echo "<img style=\"padding:7px\" class=\"uk-card uk-card-default uk-card-hover uk-card-body\" src=\"$photo\">"; echo "</a>";}?>

UIkit php 文件夹库https: //webshel​​f.eu/en/php-folder-gallery/

get all the images from a folder in php without database


$url='https://demo.com/Images/sliderimages/';
       $dir = "Images/sliderimages/";
        $file_display = array(
            'jpg',
            'jpeg',
            'png',
            'gif'
        );
        
        $data=array();
        
        if (file_exists($dir) == false) {
            $rss[]=array('imagePathName' =>"Directory  '$dir'  not found!");
            $msg=array('error'=>1,'images'=>$rss);
             echo json_encode($msg);
        } else {
            $dir_contents = scandir($dir);
        
            foreach ($dir_contents as $file) {
                @$file_type = strtolower(end(explode('.', $file)));
                // $file_type1 = pathinfo($file);
                // $file_type= $file_type1['extension'];
                
                if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
                   $data[]=array('imageName'=>$url.$file);
               
                   
                }
            }
            if(!empty($data)){
                $msg=array('error'=>0,'images'=>$data);
                echo json_encode($msg);
            }else{
                $rees[]=array('imagePathName' => 'No Image Found!');
                $msg=array('error'=>2,'images'=>$rees);
                echo json_encode($msg);
            }
        }
// Store your file destination to a variable
$fileDirectory = "folder1/folder2/../imagefolder/";
// glob function will create a array of all provided file type form the specified directory
$imagesFiles = glob($fileDirectory."*.{jpg,jpeg,png,gif,svg,bmp,webp}",GLOB_BRACE);
// Use your favorite loop to display
foreach($imagesFiles as $image) {
    echo '<img src="'.$image.'" /><br />';
}

您可以简单地显示您的实际图像目录(不太安全)。 只需 2 行代码。

 $dir = base_url()."photos/";

echo"<a href=".$dir.">Photo Directory</a>";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM