websitebaker module: Random pic with text
November 29, 2007 1 Comment
This module includes a function you can call to randomly pick an image from a directory. It is based on a module written by John Maats, and I just added the captioning.
<?php
/* Random image snippet
Call this nsippet with:
RandomImage ('/media');
in your template */
function RandomImage($dir) {
//read folder and get the picture names
$folder=opendir(WB_PATH.$dir.'/.');
while ($file = readdir($folder))
$names[count($names)] = $file;
closedir($folder);
//remove any non-images from array
$tempvar=0;
for ($i=0;$names[$i];$i++){
$ext=strtolower(substr($names[$i],-4));
if ($ext==".jpg"||$ext==".gif"||$ext==".png"){
$names1[$tempvar]=$names[$i];$tempvar++;
}
}
//random
srand ((double) microtime() * 10000000);
$rand_keys = array_rand ($names1, 2);
//random image from array
$image=$names1[$rand_keys[0]];
//name of image for alt text
$name=substr($image,0,-4);
//print associated Text
echo "<p><b>$name</b></p>";
//read in the file if it exists
if(file_exists(WB_PATH.$dir . '/' . "$name" . ".txt"))
{
$myfile=file(WB_PATH.$dir . '/' . "$name" . ".txt");
echo '<p>';
foreach ($myfile as $val)
{
echo "$val ";
}
echo '</p>';
}
//image dimensions
$dimensions = GetImageSize(WB_URL.$dir.'/'.$image);
echo '<img src="'.WB_URL.$dir.'/'.$image.'" alt="'.$name.' image" />';
}
?>


