如何在网页中显示随机图片


How to show a random picture in a web page?

我的网站在某个地方有一个图像,当用户重新加载页面时,他应该在同一位置看到不同的图像。我有 30 张图像,我想在每次重新加载时随机更改它们。我该怎么做?

用你拥有的"图片信息"(文件名或路径)创建一个数组,比如

$pictures = array("pony.jpg", "cat.png", "dog.gif");

并通过以下方式随机调用该数组的元素

echo '<img src="'.$pictures[array_rand($pictures)].'" />';

看起来很奇怪,但有效。

选择随机图像的实际行为需要一个随机数。 有几种方法可以帮助解决这个问题:

  • rand()用于生成随机数。
  • array_rand()用于从数组中选择随机元素的索引。

如果您专门处理数组,则可以将第二个函数视为使用第一个函数的快捷方式。 因此,例如,如果您有一个图像路径数组,可以从中选择要显示的图像路径,则可以像这样随机选择一个:

$randomImagePath = $imagePaths[array_rand($imagePaths)];

如果您以未指定的其他方式存储/检索图像,那么您可能无法轻松使用array_rand()。 但是,最终,您需要生成一个随机数。 因此,rand()的一些用途将为此起作用。

如果将

信息存储在数据库中,还可以选择随机图像:

MySQL:

SELECT column FROM table
ORDER BY RAND()
LIMIT 1

PgSQL:

SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

最好菲利普

在弹出窗口中创建随机图像的一种简单方法是下面的这种方法。

(注意:您必须将图像重命名为"1.png"、"2.png"等)

<?php
//This generates a random number between 1 & 30 (30 is the
//amount of images you have)
$random = rand(1,30);
//Generate image tag (feel free to change src path)
$image = <<<HERE
<img src="{$random}.png" alt="{$random}" />
HERE;
?>
* Content Here *
<!-- Print image tag -->
<?php print $image; ?>

这种方法很简单,每次需要随机图像时我都会使用它。

希望这有帮助! ;)

我最近写了这篇文章,它在每个页面加载上加载不同的背景。只需将常量替换为图像的路径即可。

它的作用是遍历您的图像目录并从中随机选择一个文件。这样,您就不需要跟踪数组或数据库或其他任何图像。只需将图像上传到您的图像目录,它们就会被选中(随机)。

像这样打电话:

$oImg = new Backgrounds ;
echo $oImg -> successBg() ;

<?php
class Backgrounds
{
  public function __construct()
  {
  }
  public function succesBg()
  {  
    $aImages = $this->_imageArrays( 'constants'IMAGESTRUE, "images/true/") ; 
    if(count($aImages)>1)
    {
      $iImage   = (int) array_rand( $aImages, 1 ) ;
      return $aImages[$iImage] ;
    }
    else
    {
      throw new Exception("Image array " . $aImages . " is empty");
    }
  }

  private function _imageArrays( $sDir='', $sImgpath='' )
  {
    if ($handle = @opendir($sDir)) 
    {
      $aReturn = (array) array() ;
      while (false !== ($entry = readdir($handle))) 
      {
        if(file_exists($sDir . $entry) && $entry!="." && $entry !="..")
        {
          $aReturn[] = $sImgpath . $entry ;
        }
      }
      return $aReturn ;
    }
    else
    {
      throw new Exception("Could not open directory" . $sDir . "'" );
    }
  }
}
?>