PHP显示目录中的随机图像

时间:2017-09-26 22:01:10

标签: php image random unique

我是PHP的新手。

我正在寻找一种方法让PHP显示来自目录的6个随机JPG图像,无论图像名称是什么。另一个重要的是所有显示的图像应该是不同的。

您是否知道最简单的方法是什么? 我知道我应该使用glob函数,但是如何将图像限制为6,随机且不可重复?

我现在把它作为代码:

<?php
    $pictures = glob("images/gallery/*.jpg"); 
    $no_pictures = count($pictures)-1;  
    $limit = $no_pictures-5;            
    for( $i = $no_pictures; $i >= $limit; $i--){ 
    echo '<div class="col-md-4 col-sm-6 col-xs-12 wow fadeInUp">
            <a class="thumb" href="'.$pictures[$i].'"><img src="'.$pictures[$i].'" alt="Gallery"/><span class="thumb_overlay"></span></a>
          </div>'; 
}  
?>          

但是在图像刷新时,它没有显示不同的图像,它只是随机抽取6并一直显示它们。

1 个答案:

答案 0 :(得分:-1)

文件:(使用随机名称)

images/header/rotate.php
images/header/abstract.jpg
images/header/bird.jpg
images/header/butterfly.jpg
images/header/happy.jpg

HTML:

<img src="images/header/rotate.php" alt="Header" width="400" height="100" />

PHP:

<?php

/*
Check it out for more interesting scripts & downloads

AUTOMATIC IMAGE ROTATOR
Version 2.2 - December 4, 2003
Copyright (c) 2002-2003 Dan P. Benjamin, Automatic, Ltd.
All Rights Reserved.
http://www.hiveware.com/imagerotator.php

*/

$folder = '.';


$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';


// You don't need to edit anything after this point.


// --------------------- END CONFIGURATION -----------------------

$img = null;

if (substr($folder,-1) != '/') {
$folder = $folder.'/';
}

if (isset($_GET['img'])) {
$imageInfo = pathinfo($_GET['img']);
if (
    isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
      file_exists( $folder.$imageInfo['basename'] )
      ) {
      $img = $folder.$imageInfo['basename'];
    }
    } else {
    $fileList = array();
    $handle = opendir($folder);
    while ( false !== ( $file = readdir($handle) ) ) {
    $file_info = pathinfo($file);
    if (
        isset( $extList[ strtolower( $file_info['extension'] ) ] )
    ) {
        $fileList[] = $file;
    }
}
closedir($handle);

if (count($fileList) > 0) {
    $imageNumber = time() % count($fileList);
    $img = $folder.$fileList[$imageNumber];
    }
}

if ($img!=null) {
    $imageInfo = pathinfo($img);
    $contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
        header ($contentType);
     readfile($img);
} else {
if ( function_exists('imagecreate') ) {
    header ("Content-type: image/png");
    $im = @imagecreate (100, 100)
        or die ("Cannot initialize new GD image stream");
    $background_color = imagecolorallocate ($im, 255, 255, 255);
    $text_color = imagecolorallocate ($im, 0,0,0);
    imagestring ($im, 2, 5, 5,  "IMAGE ERROR", $text_color);
    imagepng ($im);
    imagedestroy($im);
    }
}

?>

旋转脚本的功劳 http://old.marcofolio.net/webdesign/php_random_image_rotation.html