Pinterset-style image gallery

Submitted by Brian on September 11, 2013 - 2:28pm
Build an very simple image gallery that compiles from a directory of images


As the summer comes to a close I finally am getting caught up on the various different projects that I said I was going to do. well, one of those is putting up the images from my wedding this summer! In any attempt to use an "easy" social sharing photo gallery like Google +, I became frustrated that my family that didn't have a google+ account could not access the photos. So, I decided to build my own!

Since I had some 300 images, I decided it would be best to build a script that would scrape a folder for images and pull them in. To do this I modified a simple PHP script that would build all the images on the page.

Essentially it looks in the directory, pulls out each image and places it in a DIV inside my #Gallery.

The PHP looks like this:

<?php

$directory = 'gal';

$allowed_types=array('jpg');
$file_parts=array();
$ext='';
$title='';
$i=0;

$dir_handle = @opendir($directory) or die("Accidentally the entire directory.");

while ($file = readdir($dir_handle))
{
if($file=='.' || $file == '..') continue;

$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));

$title = implode('.',$file_parts);
$title = htmlspecialchars($title);
if(in_array($ext,$allowed_types))
{
echo '
<div class="pic"><a class="fancybox" title="'.$title.'" href="'.$directory.'/'.$file.'">
<img src="'.$directory.'/'.$file.'" /></a>
</div>';

$i++;
}
}
closedir($dir_handle);

?>

Then I was like, well it would be fun to display it Pinterest style. So I used this script: Masonry JS which took all my divs and arranged them nicely. This was pretty simple just by invoking the script and telling it what DIV's to look for:

<script>
docReady( function() {
  var container = document.querySelector('#gallery');
  var msnry = new Masonry( container, {
    columnWidth: 220
  });

});
</script>

But alas, the script renders before all the images are loaded! This was a simple fix thanks to Imageloaded JS to wait to run Masonry until AFTER the images have loaded.

 <script>
(function($) {
var $container = $('#gallery').masonry();
// layout Masonry again after all images have loaded
$container.imagesLoaded( function() {
  $container.masonry();
});
})(jQuery);
</script>

Lastly, I built in FancyBox to display the images in a model.

<script type="text/javascript">
$(document).ready(function() {
$('.fancybox').fancybox({
openEffect  : 'elastic',
opacity     : 'true',
overloayOpacity: '0.6'
})
});
</script>

And thats it! now you have a simple fun gallery.

Future enhancements would be implementing some sort of lazyloader of images so that I am not loading the entire directory at once (currently 14MB of images!). Also I'd integrate a commenting system in the model.

Take a look at the gallery >