Skip to main content
Legend
January 30, 2015
Answered

Slideshow of images from a directory/folder?

  • January 30, 2015
  • 3 replies
  • 33920 views

Ok, so normally one would do something like:

<div id="slide_show">

<img src="slide_show_images/penguin.jpg alt="">

<img src="slide_show_images/lion.jpg alt="">

<img src="slide_show_images/bear.jpg alt="">

<img src="slide_show_images/elephant.jpg alt="">

</div>

Hook up a jQuery script like 'cycle' and away it goes - which is ok BUT I have 50 images I want to fade in and out prefferably random as well.

The question is has anyone found a script, used a script, that can look for images in a directory/folder, choose a randon starting point and cycle through them fading in and out?

I thought I had found something but all the image names have to take the form of IM_1.jpg, IM_2.jpg, IM_3.jpg which I cant do for reason I shall not explain.

These images are names in a database field so I could just loop through them all BUT that would put 50 images on the page which is a hefty amount of data, which will most likely slow the page down?

Cheers

Os

This topic has been closed for replies.
Correct answer Nancy OShea
Hii 

Can you please add the whole code for example?


You can get code directly from the developer's site.

http://jquery.malsup.com/cycle2/demo/

3 replies

Inspiring
September 24, 2015

I apologize for reviving this post after several months, but I'm having a similar issue myself and the codes suggested in this thread are the closest I've gotten to an answer.

Essentially, I'm trying to create a gesture drawing tool for myself (similar to this site if anyone needs an example). I can't figure out a way to display photos one at a time. I need this to work with a ton of photos; my "people" folder is almost 8,000 pictures, and that's just one category.

When I tried Nancy's code, all the buttons on the page disappeared, and when I tried Os' code, it tried to post every single photo to the webpage at once....which made my computer freeze. I need a slideshow that will pull one image from the appropriate folder at a time. While I was looking at the source for Pixelovely (the link above), I noticed only two images were added to the resources at a time. It's not like my site where every photo is immediately loaded. I don't know enough about programming and webdesign to understand how they did that just by looking at the script. But if I can get that function to work, I think it will give me the slideshow I want and stop my computer from freezing any time I use the folder with 7700+ photos.

I hope this I'm making sense. I never feel like I explain this very well. It probably doesn't help that I'm tired.

For record, here's the code from my PHP file, currently using Os' code:

<div id='pics'>

   <?php

        $allppl = glob("Allppl2/*.*");

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

        $num = $allppl[$i];

        echo '<img src="'.$num.'" />';

        }

    ?>

</div>

And here 's a snippet from the JS file:

$(document).ready(function () {

    'use strict';

    $('#pics').hide();

    $('.play').hide();

   

    //Slideshow Functions

    $('#start').click(function () {

        var allppl = '<?php echo $allppl;?>';

        $('#pics').load(allppl);

        if ($('input[name=ppl]:checked').val() == 30) {

            $('#pics').show(function () {

                $(allppl).cycle({

                    fx: 'fade',

                    next: '#pics',

                    timeout: 30000,

                    random: 1

                });

            });

osgood_Author
Legend
September 24, 2015

This may help. I have found a simple way using php for you to get a 'quantity' of random images from an image folder and put them into a slideshow using the cycle2 slideshow.

Include these 2 scripts in your page:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script src="http://malsup.github.com/jquery.cycle2.js"></script>

Include the following php and set a directory for your images:

<?php

$images = array();

$directory = 'images';

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

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

if (preg_match("/\.png$/", $file)) $images[] = $file;

elseif (preg_match("/\.jpg$/", $file)) $images[] = $file;

elseif (preg_match("/\.jpeg$/", $file)) $images[] = $file;

elseif (preg_match("/\.gif$/", $file)) $images[] = $file;

}

shuffle($images);

closedir($handle);

}

?>

Include the slideshow <div> in  your page: (This cycles through 10  images - set the number to your requirement)

<div class="cycle-slideshow">

<?php

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

echo '<img src="images/'.$images[$i].'" alt="" >';

}

?>

</div>

Inspiring
September 26, 2015

Niknab0417 wrote:


I am using Cycle 2. I can't figure out what I'm doing wrong.

This isn't cycle2 js?

$('#start').click(function () {

        var allppl = $.post('gest-slideshow.php');

        if ($('input[name=ppl]:checked').val() == 30) {

            $('#pics').show(function () {

                $(allppl).cycle({

                    fx: 'fade',

                    next: '#pics',

                    timeout: 30000,

                    random: 1

                });

            });

All you need to do is literally copy the code below and change the directory for the images (shown in red) then insert the 'cycle-slideshow' <div> in the page where you want the slideshow and change the path to the images src (shown in red)

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script src="http://malsup.github.com/jquery.cycle2.js"></script>

<?php

$images = array();

$directory = 'images';

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

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

if (preg_match("/\.png$/", $file)) $images[] = $file;

elseif (preg_match("/\.jpg$/", $file)) $images[] = $file;

elseif (preg_match("/\.jpeg$/", $file)) $images[] = $file;

elseif (preg_match("/\.gif$/", $file)) $images[] = $file;

}

shuffle($images);

closedir($handle);

}

?>

<div class="cycle-slideshow">

<?php

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

echo '<img src="images/'.$images[$i].'" alt="" >';

}

?>

</div>


Okay, the slideshow is working (yay!), but the timers I put on the page are off. I had it set up so that when I checked certain radio buttons, the photos were appear on screen for a given amount of time. Now, they all appear on screen for 5 seconds.

EDIT: I changed the div class from "cycle-slideshow" back to "pics," and that seemed to be enough to get everything in order again. A small part of me is still expecting some other problem to pop up.

<div class="pics" data-cycle-center-horz=true data-cycle-center-vert=true>

   <?php

        $images = array();

        $directory = './Allppl2';

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

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

        if (preg_match("/\.png$/", $file)) $images[] = $file;

        elseif (preg_match("/\.jpg$/", $file)) $images[] = $file;

        elseif (preg_match("/\.jpeg$/", $file)) $images[] = $file;

        elseif (preg_match("/\.gif$/", $file)) $images[] = $file;

        }

        shuffle($images);

        closedir($handle);

        }

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

        echo '<img src="Allppl2/'.$images[$i].'" alt="" >';

        }

    ?>

</div>

$(document).ready(function () {

    'use strict';

    $('.pics').hide();

    $('.play').hide();

   

    //Slideshow Functions

    $('#start').click(function () {

        if ($('input[name=ppl]:checked').val() == 30) {

            $('.pics').show(function () {

                $(this).cycle({

                    fx: 'fade',

                    next: '.pics',

                    timeout: 30000,

                    random: 1

                });

            });

Nancy OShea
Community Expert
Community Expert
January 30, 2015

I wrote a php script for a client that uses jQuery Cycle to fade through a directory of images on server.  Although this isn't random b/c the client specifically wanted slides to appear in order by filename. 

<script type="text/javascript">

$(document).ready(function(){
      $('#myslides2').cycle({
      fx: 'fade', 
      speed: 5000,
      timeout: 1000
      });
});
</script>

<div id="myslides2">

<!--begin dynamic slides-->

<?php

$directory = '../GALLERY/slides/'; //path to slides folder on server

$allowed_types = array('jpg','jpeg','gif','png'

);
$aFiles = array();
$dir_handle = @opendir($directory) or die("There is an error with your image directory!");
while ($file = readdir($dir_handle)) //traverse through directory
{
if($file=='.' || $file == '..') continue; //skip links to parent directories
$file_parts = explode('.',$file); //split file parts and put each into an array
$ext = strtolower(array_pop($file_parts)); //last part is extension
$title = implode('.',$file_parts); //what's left is filename
$title = htmlspecialchars($title); //make the filename html-safe
if(in_array($ext,$allowed_types))
{
$aFiles[] = $file;
}
}
closedir($dir_handle); //close directory
natsort($aFiles); // natural sort filenames
$i=0; //loop
foreach ($aFiles as $file) { //repeat as before
$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));
$title = implode('.',$file_parts);
$title = htmlspecialchars($title);
    echo '<img src=" '.$directory.'/'.$file.'" alt="Art by XYZ..." />'
;
}
?>
</div>
<!--end myslides2-->

It goes without saying, you'll need to add links to the jQuery core library and Cycle plugin.

Nancy O.

Nancy O'Shea— Product User & Community Expert
osgood_Author
Legend
January 31, 2015

Hi Nancy,

Thanks, the issue I see with doing it the way you suggest (and the way I'm currenty using) is that ALL the images are echoed to the page, right. I used a similar method (below) as I could'nt find a way of just requesting each image from the folder when required, to keeep the page load time to a minimum. Whilst it works locally just fine, fast, I have not tested on a remote server. Loading 50 images to a page must take its toll I assume.

<?php

$files = glob("assets/random_slideshow/*.*");

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

{

$num = $files[$i];

echo '<img src="'.$num.'" alt="" />';

}

?>

Then I used as you did (cycle2) and just added the random option.

<script>

/* random image slide show */

$('#image_rotate').cycle({

random: 1

});

</script>

Os

BenPleysier
Community Expert
Community Expert
January 30, 2015

Hi osgood_,

I have not tried this, but it should work for you. The idea is to use the free DMXZone HTML5 Data Source extension on a local JSON file containing the names and paths of the images. The JSON file can be created from the database or it can be constructed manually. You could also use the database directly but then you would have to purchase the Database Connector.

Another way is to upload the images to a public feed like Flickr or Picasa with the same result.

Theoretically, the file names/paths will be loaded and used when the image is  rendered.

Wappler is the DMXzone-made Dreamweaver replacement and includes the best of their powerful extensions, as well as much more!
osgood_Author
Legend
January 31, 2015

Ben Pleysier wrote:

Hi osgood_,

I have not tried this, but it should work for you. The idea is to use the free DMXZone HTML5 Data Source extension on a local JSON file containing the names and paths of the images. The JSON file can be created from the database or it can be constructed manually. You could also use the database directly but then you would have to purchase the Database Connector.

Another way is to upload the images to a public feed like Flickr or Picasa with the same result.

Theoretically, the file names/paths will be loaded and used when the image is  rendered.

Hi Ben,

Interesting, does this option only load the current image to the page as requested, therfore keeping the page load to a minimum?

Thats ideally what I would like but don't really undertand how it works.

Os

BenPleysier
Community Expert
Community Expert
January 31, 2015

In theory, the images will be loaded as required. Looking at Nancy's code makes me think that her way is probably the go.

Sooner or later the image will have to be loaded, so there is no advantage to be gained by spreading them.

There are a number of other good practices to follow when optimizing a website, namely

  • Minimizing HTTP Requests : Combine CSS into one file; combine JS into one file; combine images into a sprite.
  • Minifying HTML, CSS & JavaScript : self explanatory
  • Optimizing Images : using PNG is often (not always) the best option; use original size where possible.
  • Caching : see Leverage Browser Caching - PageSpeed Insights — Google Developers and PHP Image Cache for images
  • Deferring Parsing of Javascript : Load JS last, i.e. bottom of document
Wappler is the DMXzone-made Dreamweaver replacement and includes the best of their powerful extensions, as well as much more!