从文件夹中随机抽取图片的PHP代码

6

我想知道从文件夹中获取随机图片的“更好”方法。

比如说,让php直接从文件夹中选择一张随机图片,而不是搜索并创建一个数组。

以下是我目前的做法:

<?php
    $extensions = array('jpg','jpeg');
    $images_folder_path = ROOT.'/web/files/Header/';
    $images = array();
    srand((float) microtime() * 10000000);

    if ($handle = opendir($images_folder_path)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                $ext = strtolower(substr(strrchr($file, "."), 1));
                if(in_array($ext, $extensions)){
                $images[] = $file;
                }
            }
        }
    closedir($handle);
    }
    if(!empty($images)){
        $header_image = $images[array_rand($images)];
    } else {
        $header_image = ''; 
    }
?>
4个回答

12

试试这个:

<?php

$dir = "images/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>

<img src="images/<?php echo $images[$i]; ?>" alt="" />

你的回答很好,而且简短!但是有一个问题!如果图像目录包含大量图像(1K),scandir 将把它们全部加载到数组中。然而,你只需要一张图片。有没有办法改进你的回答?如果你可以将其封装在一个函数中,并提供获取有限数量图像的选项,例如 $returned_images_count=10;,我的意思在 这个问题 中已经部分解释了。此外,在性能分析中,opendir 看起来更快。 - wpcoder

1

以下代码通过图像扩展名验证图像列表。

<?php function validImages($image) { $extensions = array('jpg','jpeg','png','gif'); if(in_array(array_pop(explode(".", $image)), $extensions)) { return $image; } } $images_folder_path = ROOT.'/web/files/Header/'; $relative_path = SITE_URL.'/web/files/Header/'; $images = array_filter(array_map("validImages", scandir($images_folder_path))); $rand_keys = array_rand($images,1);
?>
<?php if(isset($images[$rand_keys])): ?> <img src="<?php echo $relative_path.$images[$rand_keys]; ?>" alt="" /> <?php endif; ?>

1
function get_rand_img($dir)
{
    $arr = array();
    $list = scandir($dir);
    foreach ($list as $file) {
        if (!isset($img)) {
            $img = '';
        }
        if (is_file($dir . '/' . $file)) {
            $ext = end(explode('.', $file));
            if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png' || $ext == 'GIF' || $ext == 'JPEG' || $ext == 'JPG' || $ext == 'PNG') {
                array_push($arr, $file);
                $img = $file;
            }
        }
    }
    if ($img != '') {
        $img = array_rand($arr);
        $img = $arr[$img];
    }
    $img = str_replace("'", "\'", $img);
    $img = str_replace(" ", "%20", $img);
    return $img;
}


echo get_rand_img('images');

将“images”替换为您的文件夹。


0

我在网上搜索了数小时,才实现了我想要的代码。我汇集了我在网上找到的各种答案的片段。以下是代码:

<?php
    $folder = opendir("Images/Gallery Images/");
    $i = 1;
    while (false != ($file = readdir($folder))) {
        if ($file != "." && $file != "..") {
            $images[$i] = $file;
            $i++;
        }
    }
    //This is the important part... 
    for ($i = 1; $i <= 5; $i++) { //Starting at 1, count up to 5 images (change to suit)
        $random_img = rand(1, count($images) - 1);
        if (!empty($images[$random_img])) { //without this I was sometimes getting empty values
            echo '<img src="Images/Gallery Images/' . $images[$random_img] . '" alt="Photo ' . pathinfo($images[$random_img], PATHINFO_FILENAME) . '" />';
            echo '<script>console.log("' . $images[$random_img] . '")</script>'; //Just to help me debug
            unset($images[$random_img]); //unset each image in array so we don't have double images
        }
    }
?>

使用这种方法,我能够在没有错误的情况下实现opendir (因为glob()对我来说不起作用),我能够为旋转木马画廊获取5张图片,并且消除了重复的图片并解决了空值的问题。使用我的方法的一个缺点是,画廊中的图像数量在3到5之间变化,可能是由于删除了空值导致的。这并不太困扰我,因为它按照需要工作。如果有人能让我的方法更好,我欢迎你这样做。 工作示例(网站顶部的第一个旋转木马画廊): Eastfield Joinery


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接