Search code examples
phpimagedirectoryreloadjquery-backstretch

Pull images from folder for Backstretch


since I could not find the answer anywhere maybe someone else is troubled by this too. I would like to use random images from a folder in backstretch without specifing the images before. I am not good at php, so could someone tell me how to do this, I believe it would be sth. similar to this solution, which is for supersized (How to use the Supersized! plugin with image folders)

Furthermore I'd need the slideshow to start with a different image when the page is reloaded/revisited.

Thanks a lot for helping me!!


Solution

  • I've put together a simple php script. It gets all .jpg's from $image_dir and returns them in a random order.

    The first image is saved as a session variable, and after a refresh a new image gets picked and added to the start of the array.

    The code is pretty basic, if you have subfolders you'd have to customize it:

    PHP:

    <?php
    //Start Session
    session_start();
    
    
    function GetRandomImagesFromDir( $image_dir ) {
    //Create image array
    $images = glob($image_dir . '*.jpg');
    
    
    //Get first image
        //Get one random image from array
        $rand_key = array_rand($images, 1);
    
        //Same image as before?
        if ( $rand_key == $_SESSION['last_image'] ) {
            if ( $rand_key > 1 ) {
                $rand_key--;
            } else {
                $rand_key++;
            }
        }
    
        //Save Key to Session
        $_SESSION['last_image'] = $rand_key;
    
        //Save image to var
        $first_image = $images[ $rand_key ];
    
    
    //Get next images
        //Remove first-image from array
        unset( $images[ $rand_key ] );
    
        //Shuffle
        shuffle( $images );
    
        //Add first image
        $images[] = $first_image;
    
        //Reverse array
        $images = array_reverse($images);
    
    
    //Array to string
        $return_str = implode('","', $images);
        $return_str = '"'.$return_str.'"';
    
    
    //Return string
    return $return_str;
    }
    ?>
    

    JS:

    <script>
        $.backstretch([<?=GetRandomImagesFromDir('backstretch_images/')?>]);
    </script>