Randomize slideshow images - php

I have this drupal slideshow which pulls images from a folder sequentially by image title (01_title.jpg, 02_title.jpg, etc..)
I was wondering if there is an easy way to randomize the images, so it starts with a different image every time you refresh the page?
you can view the slideshow here http://www.rubensteinpr.com/
Thanks!
<div id ="index">
<?php
// Note that !== did not exist until 4.0.0-RC2
$desired_extension = 'jpg'; //extension we're looking for
$banner_imgs_array = array(); // array of banner images
$banner_imgs = ''; // sting of banner images names comma dileneated
if ($handle = opendir(file_directory_path().'/banner_imgs')) {
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if(($file != ".") and ($file != "..")) {
$fileChunks = explode(".", $file);
if($fileChunks[1] == $desired_extension) //interested in second chunk only
{
$banner_imgs_array[] = $file;
}
}
}
closedir($handle);
$banner_imgs = implode(',', $banner_imgs_array);
}
?>
<div id="banner"><img src="<?php print file_directory_path(); ?>/temp_banner.jpg" width="702" height="310" border="0"></div>
<div id="bannerText">media relations • strategic planning • digital communications • crisis management</div>
<script type="text/javascript">
// <![CDATA[
var so = new SWFObject("<?php print file_directory_path(); ?>/banner.swf", "ban", "702", "310", "8", "#ffffff");
so.addParam('menu', 'false');
so.addParam("wmode", "transparent");
so.addParam("base", "<?php print file_directory_path(); ?>");
so.addVariable("banner_imgs", "<?php print $banner_imgs; ?>");
so.write("banner");
// ]]>
</script>
</div>

adding
shuffle($banner_imgs_array);
line just before
$banner_imgs = implode(',', $banner_imgs_array);
should do the trick.

array_rand will return one or more random array keys. If you want to shuffle the array itself, use shuffle.

Related

Randomize photos from a directory via PHP

I have the following code that is functional that will randomize the photos I have in my 'photos' folder each time the refresh button is clicked. I know this may not be the most efficient way for this to be coded but for my matter it works. I am looking for help regarding my PHP code that will make the photos more random. I currently have 200+ pictures in the folder and often get repeated pictures more than I'd like. What changes to it can I make? (PS. ignore the AJAX/JavaScript I was playing around with)
<html>
<head>
<title>Pictures!</title>
<style type="text/css">
body{ background-color:D3DFDE; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
</head>
<body>
<div id='main'>
<?php
function randomimages(){
$dirname = isset($_REQUEST['dir'])? $_REQUEST['dir'] : './photos/';
$numimages = isset($_REQUEST['num'])? $_REQUEST['num'] : 1;
$pattern = '#\.(jpg|jpeg|png|gif|bmp)$#i';
$files = array();
if($handle = opendir($dirname)){
while(($file = readdir($handle)) !== false){
if(preg_match($pattern, $file)){
array_push($files, "<center><img src='" . $dirname . $file . "' alt='' /></br><br/><hr/></center>");
}
}
closedir($handle);
shuffle($files);
}
return implode("<center><br/>", array_slice($files, 0, $numimages)) . "<br/> </center>";
}
?>
<!-- <center><a id="myButton" href="#">MAS PICTURES!</a></center> -->
<center><input type='button' onClick='window.location.reload(true)' value='MAS PICTURES!!!' style="height:200px; width:150px" /></center>
<hr/>
<script type="text/javascript">
$(function() {
$("#myButton").click(function() {
$("#main").load("index.php");
});
});
</script>
<?php echo randomimages(); ?>
<center>Created by: Matt & Joe</center>
</div>
</body>
</html>
You can do the following:
Optimize the code by not reading the directory over and over. What you can do this by reading the directory once (and say then store the entries as an array in APC cache). Set a timeout for this APC key to bust the cache once in a while.
Call the `mt_rand` function with min as `0` and max as `count(array)-1` and access that index.
Generic code to read from directory can be as follows (needs modification to match your needs):
<?php
function &list_directory($dirpath) {
if (!is_dir($dirpath) || !is_readable($dirpath)) {
error_log(__FUNCTION__ . ": Argument should be a path to valid, readable directory (" . var_export($dirpath, true) . " provided)");
return null;
}
$paths = array();
$dir = realpath($dirpath);
$dh = opendir($dir);
while (false !== ($f = readdir($dh))) {
if (strpos("$f", '.') !== 0) { // Ignore ones starting with '.'
$paths[] = "$dir/$f";
}
}
closedir($dh);
return $paths;
}
Provide the directory full path to the variable $dirpath
$image_source_array=scandir($dirpath);
sort($image_source_array);
Use mt_rand function with min as 0 and max as count($image_source_array)-1 and access that index from the array to get the image name
and then access the image with the $dirpath/image name you will get the random image each time
Create function like this it will be the shortest approch
function randomimages() {
$dirname = isset($_REQUEST['dir']) ? $_REQUEST['dir'] : './photos/';
$image_source_array = scandir($dirname);
sort($image_source_array);
$image_count = count($image_source_array) - 1;
$rand_index = mt_rand(3, $image_count);
//Starting with 3 because scandir returns directory also in the 2 indexes like '.' and '..'
$rand_image_path = $dirname . $image_source_array[$rand_index];
return $rand_image_path;
}
For the sake of simplicity and reusability, you might want to use RegexIterator together with DirectoryIterator:
function randomimages($path, $num_images)
{
$images = array();
foreach (new RegexIterator(new DirectoryIterator($path),
'#\.(jpe?g|gif|png|bmp)$#i') as $file) {
$images[] = $file->getPathname();
}
shuffle($images);
return array_slice($images, 0, $num_images);
}
Using:
$path = isset($_REQUEST['dir']) ? $_REQUEST['dir'] : './photos/';
$num_images = isset($_REQUEST['num']) ? $_REQUEST['num'] : 1;
print implode('<br />', randomimages($path, $num_images));

Listing directory of images into dropdown and remembering selection

I have this code to list the images in a directory into a dropdown so that I can then select an image and save the image name selected into a flat file for later use in other programs/scripts. When I come back to make changes I have to re-select the image and I would like to be able to have it remember the image as selected via the variable.
It's been a while since I've been fluent in php as I've been undergoing medical treatments and the medicine has affected my memory and I've tried to work out an elseif statement but it wasn't successful, I think the while loop is overriding it. The functions file sorts the directory files and the info file is the flat file. It works, except it doesn't allow me to show the selected image in the dropdown menu when the page is reloaded.
Thanks in advance for any help.
<?php
include ("functions.php");
include ("info_file1.php");
// Settings section ------------------------------
$filedir = "files/"; // The file folder
$columns = 1; // Number of columns of files listed per row
global $filename;
global $filename_sorted;
$i=0;
$j=0;
$k=0;
$m=0;
// Table Title row -------------------------------
echo "<select name=Image id=Image>";
if (file_exists($filedir)) {
$handle = opendir($filedir);
while (false !==($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$filename[$i][1] = $file;
$filename[$i][2] = date ("m/d/y", filemtime($filedir.$file));
$filename[$i][3] = round(filesize($filedir.$file)/1024);
++$i;
}
}
closedir($handle);
// Sorting --------------------------------------------
$filename_sorted = ($filename);
// End of Sorting -------------------------------------
while($m<(count($filename)))
{
echo "<option value=".$filename_sorted[$m][1].">".$filename_sorted[$m][1]."</option>";
$m++;
}
} elseif ( $image=$filename_sorted[$m][1] )
echo "<option value=".$image." selected>".$image."</option>";
else {
echo "<option value=Upload Image First>Upload Image First</option>";
}
echo "</select>";
?>

Display images from directory with PHP

i'm new to PHP and jQuery but i would like to do the following things to a portfolio that i'm developing using easySlider and Lightbox plugin:
Display a limit of six images or six div images per "li" tag and close it from a directory.
If there is more than six images on the directory, create a new "li" tag and show six more images, till all the images from that directory are loaded.
If an image has a name with a number after -> display: Hidden. For example: beta1 but i only want to show the first one "beta"
Sort images by name.
Don't let anyone access to the images on that directory, if it isn't the code itself.
The code for portfolio is the following:
<div id="portfolio_hold">
<ul>
<li>
<div class="portfolio_pic_hold">
<a href="large.jpg" rel="lightbox[]" >
<img src="thumb.jpg"/>
</a>
</div>
</li>
</ul>
</div>
This is my html example of what i want to show.
This might do the trick
$thumbsPath = "trabalhos/design/thumbs/";
$imagespath = "trabalhos/design/images/";
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if (file_exists($thumbsPath) == false)
{
echo 'Directory \'', $thumbsPath, '\' not found.';
}
else
{
$thumbs = glob($thumbsPath."*.[".implode($file_display,"|")."]");
if (file_exists($imagesPath) == false){
echo 'Directory \'', $imagesPath, '\' not found.';
} else
{
$counter = 0;
$filesPerPage = 6;
foreach ($thumbs as $file)
{
if($counter % $filesPerPage) echo "<li>";
$counter++;
$info = pathinfo($file);
$sFile = basename($file,'.'.$info['extension']);
$aFiles = glob($images.$sFile."[0-9]+.[".implode($file_display,"|")."]"); //Este array tem todas as imagens relativas ao thumbnail que estás a ver
echo "<div><img /></div>";
if($counter == $filesPerPage) echo "</li>";
}
}
}

Base an if else statement on what folder an image is from on server?

I've used php to open and list the files in the folder, but I'd like to somehow turn it into an if else statement so that if its from the 'dark' background folder a white logo will be displayed and if its from a 'light' background folder a black logo will be displayed.
<?php
//path to directory to open
$directory = "backgrounds/dark";
$dir_handle = #opendir($directory) or die("Unable to open folder");
while(false !== ($file = readdir($dir_handle)))
{
if($file != '.' && $file != '..')
{
echo "{image : 'http://occa-art.com/backgrounds/dark/".$file."'}, ";
}
}
closedir($dir_handle);
?>
The {image: 'http://' } format is used because the images are listed within the Supersized background script.
---EDIT---
Maybe something like this (untested) to determine which folder the background image is from:
<?php
$doc = new DOMDocument();
$doc->loadHTML($htmlAsString);
$xpath = new DOMXPath($doc);
$nodeList = $xpath->query('//img[#class="bg"]/#src');
for ($i = 0; $i < $nodeList->length; $i++) {
# Xpath query for attributes gives a NodeList containing DOMAttr objects.
# http://php.net/manual/en/class.domattr.php
echo $nodeList->item($i)->value . "<br/>\n";
}
$bg_url = $nodeList->item($i)->value; // not sure about this?
$parent = dirname("$bg_url");
if ($parent == 'dark') { ?>
<img src="<?php bloginfo('template_url'); ?>/images/OCCAIndexHeaderwhite.png" alt="OCCA logo" />
<?php } else { ?>
<img src="<?php bloginfo('template_url'); ?>/images/OCCAIndexHeaderblack.png" alt="OCCA logo" />
<?php } ?>
used code found here and here

Random images on click

I have code on how to random images on refresh however i wan it to be like when i click a button a random images shows up how do i do that?
Here's the code to random images:
<?
$imglist='';
//$img_folder is the variable that holds the path to the banner images. Mine is images/tutorials/
// see that you don't forget about the "/" at the end
$img_folder = "images/tutorials/";
mt_srand((double)microtime()*1000);
//use the directory class
$imgs = dir($img_folder);
//read all files from the directory, checks if are images and ads them to a list (see below how to display flash banners)
while ($file = $imgs->read()) {
if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
$imglist .= "$file ";
} closedir($imgs->handle);
//put all images into an array
$imglist = explode(" ", $imglist);
$no = sizeof($imglist)-2;
//generate a random number between 0 and the number of images
$random = mt_rand(0, $no);
$image = $imglist[$random];
//display image
echo '<img src="'.$img_folder.$image.'" border=0>';
?>
Work with JavaScript:
document.getElementById('the-img-id').onclick = function() {
var randomInt = Math.round(Math.random() * 12); // 12 is the max
this.src = '/path/to/images/img-'+randomInt+'.jpg'; // replace the src
}
This works with /path/to/images/img-1.jpg.
You can also make an array:
var myImages = [
'foo.jpg',
'bar.jpg',
'something.jpg',
'someotherting.jpg',
'ahhhanpng.png'
];
// select a element with id="the-img-id"
document.getElementById('the-img-id').onclick = function() {
var randomInt = Math.round(Math.random() * myImages.length-1 ); // Create random number
this.src = '/path/to/images/'+myImages[randomInt]; // replace the src with the new img
}
Look at the comments (after //) and google some code and you will use this succesfully.
you will need to use javascript. Use getElementById("idOfImageElement").src = "newSrc".

Categories