Tuesday, August 12, 2008

Random Image Rotation

If you find my scripts useful sign my guestbook with a link to where you're using it.


I wanted a script that would grab all the images in a directory and then randomly rotate them on my homepage. This is what I came up with.




PHP Code:






<?

function directoryToArray($directory, $recursive) {


$array_items = array();

if (
$handle = opendir($directory)) {

while (
false !== ($file = readdir($handle))) {


if (
$file != "." && $file != "..") {

if (
is_dir($directory. "/" . $file)) {


if(
$recursive) {

$array_items = array_merge($array_items, directoryToArray($directory. "/" . $file, $recursive));


}

$file = $directory . "/" . $file;

$array_items[] = preg_replace("/\/\//si", "/", $file);


} else {

$file = $directory . "/" . $file;

$array_items[] = preg_replace("/\/\//si", "/", $file);


}

}

}

closedir($handle);

}

return
$array_items;

}



$files = directoryToArray("randomimages/", false); //The Directory to grab the images from


shuffle($files);

$count=count($files);





echo
"<script>\n";


echo
"var curImage=0;\n";

echo
"var numImages=$count;\n";

echo
"var img = new Array();\n";



for (
$i=0; $i<$count; $i++){


echo
"img[$i]='$files[$i]'; \n";

}



?>



function rotate()

{  

<?


    
if (preg_match("/msie.[4|5|6]/i",$_SERVER["HTTP_USER_AGENT"]))

    {

     echo
"document.images.myimg.style.filter='blendTrans(duration=2)';\n";   //the time of duration if browser is IE

     
echo "document.images.myimg.filters.blendTrans(duration=5).Apply();\n";


     echo
"document.images.myimg.filters.blendTrans.Play();\n";

    }

?>

    document.images.myimg.src=img[curImage];

    curImage++;

    if (curImage >= numImages){

     curImage=0;}

    setTimeout("rotate()",3000);  //The time to display the image

}




</script>



  

<body onload="rotate()">



  

<img border="0" id="myimg" name="myimg" width="290" height="218" align="right">







0 comments: