从目录加载随机图像

时间:2012-01-12 17:31:12

标签: php jquery ajax random

我想从目录中随机加载图片,并在某处刷新整个页面。这是我现在的代码:

<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
  while (false !== ($file = readdir($handle))) {
    if (preg_match("/\.png$/", $file)) $a[] = $file;
    elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
    elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
  }
  closedir($handle);
}

foreach ($a as $i) {

  echo "<img src='" . $dir . '/' . $i . "' />";

}

?>  

问题是它一次加载所有400,000张图像。我只想加载30。来自目录的30个随机图像。我尝试查找一些代码,例如修改上面的代码:

<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
  while (false !== ($file = readdir($handle))) {
    if (preg_match("/\.png$/", $file)) $a[] = $file;
    elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
    elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
  }
  closedir($handle);
}

foreach ($a as $i) {

  echo "<img src='" . $dir . '/' . $i . "' />";
  if (++$i == 2) break;

}

?>  

但它似乎绝对没有。所以如果有人可以帮助我从该目录中获取30张随机照片来加载并拥有某种类型的重新加载按钮,那将会有很大的帮助。

提前谢谢

5 个答案:

答案 0 :(得分:1)

您应该只读取目录中的30个文件。当readdir返回false或者数组的长度为30时,停止查看目录。

这应该有效

    $a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
  while (false !== ($file = readdir($handle)) && (count($a) <= 30) {
    if (preg_match("/\.png$/", $file)) $a[] = $file;
    elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
    elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
  }
  closedir($handle);
}

它可能无法执行(我没试过)。但这个想法就在这里

随机化图像:shuffle($ a)应该做的伎俩

答案 1 :(得分:1)

您需要为计数器创建一个新变量,而不是使用$i

例如,您可以改为

$j = 0;
foreach ($a as $i) {
  echo "<img src='" . $dir . '/' . $i . "' />";
  $j++;
  if ($j >= 30)
  {
    break;
  }

}

编辑:也许对于随机部分,您可以先生成一个介于0和n-1之间的随机数,其中n是图像的总数,然后只是从数组中回显图像索引号。

我认为您不需要使用foreach,而是需要for循环。

$totalImgs = count($a);
$imgUsed = array();
for ($j = 0; $j < 30; $j++)
{
    do
    {
        $randIndex = mt_rand(0, $totalImgs);
    }
    while ($imgUsed[$randIndex] === TRUE);
    $imgUsed[$randIndex] = TRUE;
    echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
}

答案 2 :(得分:1)

如果您有400,000张图像,那么我认为每次阅读整个目录将是一种显示随机图像的昂贵方法。我会使用数据库代替并将文件路径存储在其中。

如果您想使用现有代码,请以这种方式考虑。您有一个包含图像名称的长度为n的数组。您希望在0n-1之间generate thirty random numbers。然后显示与阵列中该位置关联的图像。我不是一个PHP专家,但这里有一些伪代码:

$a = array(); 
$dir = '../public/wp-content/uploads/2012/01';

if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;

for ( i=0; i < 30; i++) {
     //generate a random number between 0 and N-1
     random = rand(0, $a.length - 1);
     //display that image in the array
     echo "<img src='" . $dir . '/' . $a[random] . "' />";
}

答案 3 :(得分:1)

以最简单的方式, 你可以用

find , sort , head 
linux中的

命令,结合PHP的内置

exec()

功能可以轻松获得30个随机图像链接,下面的代码片段列出了如何执行此操作 (如何在数组中获取随机的30个图像链接。)

<?php
$picdir = "directory/containing/pictures"; // directory containing only pictures
exec("find " . $picdir . " | sort -R | head -30 ",$links);
while(list($index,$val) = each($links) ) {
    echo "<img src =" .$val . "> <br/>";  // shows image 
}

&GT?; 这里$ links数组包含完整路径的随机30个图像名称(来自文件夹)。这与echo中的img标签一起使用以生成图像

这里$ picdir有目录的路径有图像,并假设dirrectory只有图像文件。在其他情况下,唯一的问题是修改find​​命令以排除非图像文件(例如使用grep命令排除)

答案 4 :(得分:1)

这是我的缓存解决方案:

<?php

define('CACHE_FILE', 'mycache.tmp');
define('CACHE_TIME', 20); // 20 seconds (for testing!)
define('IMG_COUNT', 30);
define('IMG_DIR', '../public/wp-content/uploads/2012/01');

/**
  * Loads the list (an array) from the cache
  * Returns FALSE if the file couldn't be opened or the cache was expired, otherwise the list (as an array) will be returned.
  */
function LoadListFromCache($cacheFile, $cacheTime)
{
  if ( file_exists($cacheFile) )
  {
    $fileHandle = fopen($cacheFile, 'r');
    if ( !$fileHandle )
      return false;

    // Read timestamp (separated by "\n" from the content)
    $timestamp = intval( fgets($fileHandle) );
    fclose($fileHandle);
    // Expired?
    if ( $timestamp+$cacheTime > time() )
      return false;
    else
    {
      // Unserialize the content!
      $content = file_get_contents($cacheFile);
      $content = substr( $content, strpos($content, "\n") );

      $list = unserialize($content);
      return $list;
    }
  }
  return false;
}

/**
  * Caches the passed array
  * Returns FALSE if the file couldn't be opened, otherwise TRUE.
  */
function SaveListToCache($cacheFile, $list)
{
  $fileHandle = fopen($cacheFile, 'w');
  if ( $fileHandle === FALSE ) return false;

  fwrite($fileHandle, time());
  fwrite($fileHandle, "\n");
  fwrite($fileHandle, serialize($list));

  fclose($fileHandle);
  return true;
}

/**
  * Generates the list of all image files (png, jpg, jpeg) and caches it.
  * Returns the list as an array.
  */
function GenerateList()
{
  $a = array();
  $dir = IMG_DIR;
  if ($handle = opendir($dir))
  {
    while (false !== ($file = readdir($handle)))
    {
      if (preg_match("/\.png$/", $file)) $a[] = $file;
      elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
      elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
    }
    closedir($handle);
  }
  SaveListToCache(CACHE_FILE, $a);
  return $a;
}

function GetRandomImages($list, $count)
{
  $listCount = count($list);
  $randomEntries = array();

  for ($i=0; $i<$count; $i++)
  {
    $randomEntries[] = $list[ rand(0, $listCount) ];
  }
  return $randomEntries;
}

// This code will execute the other functions!

$list = LoadListFromCache(CACHE_FILE, CACHE_TIME);

if ( $list === FALSE )
{
  $list = GenerateList();
}
$images = GetRandomImages($list, IMG_COUNT);

foreach ($images as $image)
{
  echo '<img src="', IMG_DIR.DIRECTORY_SEPARATOR.$image, '" />';
}