首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >php从文件夹中随机设置背景图像

php从文件夹中随机设置背景图像
EN

Stack Overflow用户
提问于 2016-03-27 07:35:11
回答 4查看 1.7K关注 0票数 2

我正在尝试通过PHP从文件夹中随机设置网页的背景图像。

我有以下代码:

代码语言:javascript
复制
<!DOCTYPE HTML>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css">
        <title>404</title>
    </head>

    <body id="Background404">
        <p>404-Page not found. <a href="http://url.com>Home.</a></p>
    <?php
        $dir = '/var/www/html/Images';
        $fileNames = array();
        if(is_dir($dir)){
            $handle = opendir($dir);
            while(false !== ($file = readdir($handle))){
                if(is_file($dir.'/'.$file) && is_readable($dir.'/'.$file)){
                $fileNames[] = $file;
                }
            }
            closedir($handle);
            $fileNames = array_reverse($fileNames);
            print_r($fileNames);
        }
        $totalLength = sizeof($fileNames);
        $randInt = rand(0, $totalLength);
        $randFile = $fileNames[$randInt];
        echo '<style> #Background404{background: url($randFile);}</style>';

    ?>

    </body>
</html>

注意:文件的打印只是为了确保我在代码中达到这一点,并查看文件的名称。我在这里发现了一个类似的问题:随机背景图像PHP,但是当我使用这个答案时,我只得到了一个纯白色的背景。

以下是打印数组的副本:

代码语言:javascript
复制
Array ( 
        [0] => GraniteBridge.png
        [1] => mobileBackground.png
        [2] => OtherKingdom.png
        [3] => NetherBase.png
        [4] => BackgroundTablet.png
        [5] => Snowy.png
        [6] => Village.png
        [7] => background2.png
        [8] => CactusFarm.png
        [9] => FrontView.png
        [10] => CreditsPortal.png
        [11] => FrontNight.png
        [12] => background4.png
        [13] => XPFarmRailway.png
        [14] => GoldIronFarms.png
        [15] => Pyramid.png
        [16] => NetherFortress.png
        [17] => TheEnd.png
        [18] => Library.png
        [19] => Background.png
        [20] => twitter.png
        [21] => mobileBackground1.png
        [22] => mobileBackground2.png
        [23] => BirdsEyeView.png
        [24] => EndPortal.png
        [25] => AboveVillage.png
        [26] => TowerToTheHeavens.png
        [27] => TowerArmorStands.png
        [28] => FullSizeBackground.png
        [29] => Mansion.png
        [30] => Night.png
        [31] => Dojo.png
)
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-06-12 10:31:48

可以使用兰德获取数组中的随机索引。然后,您可以使用该随机索引从数组中获取图像。

代码语言:javascript
复制
$randomImage = $images[array_rand($images)];

这是一个完整的示例,它使用格罗布获取文件夹中的图像。

代码语言:javascript
复制
<?php 
$imagesDir = '/var/www/html/images';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

$randomImage = $images[array_rand($images)];
?>

<img style="background-image:url('/path/to/images/<?php echo $randomImage ?>');"/>
票数 2
EN

Stack Overflow用户

发布于 2016-03-27 07:40:12

我们可以看到数组中的元素是按数组键升序的。我们可以利用这些信息创建一种获取随机数组元素的适当方法。

首先,您必须获取数组的计数,因此:

代码语言:javascript
复制
$count = count($fileNames);

然后,只需使用rand()函数生成从0到数组计数的随机数:

代码语言:javascript
复制
$random = rand(0, $count) - 1;

现在您有了随机数组密钥,因此您可以使用它:

代码语言:javascript
复制
<img style="background-image:url('path/to/image/<?=$fileNames[$random]?>');"/>
票数 1
EN

Stack Overflow用户

发布于 2019-06-12 11:46:05

再走一步..。

  • 它从指定的文件夹中随机选择jpgpnggif图像,
  • 将“整体”(contained)图片显示为background-image (通过html <body>标记)
  • 将页面background-color设置为图像的平均颜色
  • 显示<div>中背景图像的“短”文件名,
  • <div>的文本color设置为、黑色、White:以最佳对比度设置图像颜色。
代码语言:javascript
复制
<html>
<?php
  // get array of image filenames (jpg/png/gif) from specified folder
  $img_path="../images/";
  $imgs=glob($img_path."*.{jpg,png,gif}", GLOB_BRACE);

  // choose an image randomly
  $rnd_img = $imgs[mt_rand(0, count($imgs)-1)];

  // calc average $r,$g,$b + recommended $text_color  
  extract(text_color_from_avg_img_color($rnd_img));

  // print html <body> tag with bg image + avg bg color
  echo "<body style=\"background: rgb($r,$g,$b) url('$rnd_img'); " 
      ."background-position:center; background-size:contain; "
      ."background-repeat:no-repeat; height:100%; \">";

  //print image title in appropriate color
  echo "<div style='color:$txt_color; font-size:5vmin;'>"
      ."Random image: '".basename($rnd_img)."'</div>";


  function text_color_from_avg_img_color( $fname ) {
  /* adapted from gist.github.com/8098215 + stackoverflow.com/q/1331591 */  
    try  {  $image = new Imagick($fname); //uses Imagick to...
          $image->scaleimage(1, 1);  // scale to 1x1 pixel to get avg color
          if(!$pixels = $image->getimagehistogram())  { return 'black'; }
        } catch(ImagickException $e)                  { return 'black'; }
          catch(Exception $e)                         { return 'black'; }
    extract(reset($pixels)->getcolor()); //next calc best contrast color: 
    $L=0.2126*pow($r/255,2.2)+0.7152*pow($g/255,2.2)+0.0722*pow($b/255,2.2);
    $txt_color=((int)($L>0?(($L+0.05)/0.05):(0.05/($L+0.05)))>5?'black':'white');
    return compact("txt_color", "r", "g", "b");  //return array
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36244957

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档