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


php Setting background image randomly from folder

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

我有以下代码:

<!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,但当我使用这个答案时,我得到的只是纯白色背景。

这是打印阵列的副本:

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
)

您可以使用array_rand在数组中获取随机索引。然后你可以使用这个随机索引从你的阵列中获得图像

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

这是一个完整的例子,它使用glob来获取文件夹中的图像

<?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 ?>');"/>

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

首先你必须获取数组的计数,所以:

$count = count($fileNames);

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

$random = rand(0, $count) - 1;

现在你有了随机数组密钥,所以你可以使用它:

<img style="background-image:url('path/to/image/<?=$fileNames[$random]?>');"/>

更进一步

  • 这将从指定的文件夹中随机选择jpgpnggif图像
  • 将"整个"(contain ed)图片显示为background-image(通过html <body>标签)
  • 将页面CCD_ 4设置为图像的平均颜色
  • 显示了<div>中背景图像的"短"文件名
  • <div>的文本color设置为黑色白色:以图像颜色的对比度最佳者为准
<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
  }

为了子孙后代的利益,这里是按预期工作的原始代码。

<!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 = './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 = count($fileNames);
        $randInt = rand(0, $totalLength -1);
        $randFile = $fileNames[$randInt];
        echo $randFile;
        echo "<style> #Background404{background: url('./images/$randFile');}</style>";
    ?>
    </body>
</html>

从使用sizeof($fileNames)切换到使用count($fileNames),以避免来自其他语言的混淆,期望sizeof返回分配的内存大小。

添加完整路径,因为$fileNames只包含html期望从webroot获得路径的文件名。

-1添加到rand范围的末尾,以确保检索到有效的索引。

将单引号切换为双引号,以便变量能够正确输出