Support Forums

Full Version: PHP & jQuery picture browser
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Tried posting this on HF, but it wouldn't let me. Attempting to post it here.

This code is meant for learning, however can be used as is.

Code:
<!--

    Picture Browser
    Created by: Sly
    Date: May 9, 2010
    License: http://creativecommons.org/licenses/by-sa/3.0/
    
    Instructions:  (- Required; * Optional)
        -   Change the PHP variable $photosDir to a directory to pull the pictures from.
            This /must/ be a "url-type" directory, meaning it should follow the same
            procedures as adding the href in an <a> tag.
        *   Change the Javascript variable preload_images to a higher value if you want
            more thumbnails to be preloaded each time.
        *   Change the Javascript variable next_preload to change when images are
            preloaded again. For example, if you have 10 thumbnails loaded, with the
            default value of 7, it will preload 10 more thumbnails when you get to
            picture 3.
        
    After those very simple instructions, dummy proof, you should be able to browse to
    the page and see the content listed.
    
    Features:
        -   I'm going to call this the "SFW filter". Hit the enter key twice, and an
            overlay covers the entire page to hide anything that shouldn't be seen by
            wandering eyes. Enter twice again to hide the overlay, or click the "Remove
            Blind" link at the top of the overlay. You also have the option to display
            Google at the top of the overlay. Enter WILL NOT close the overlay if
            Google has focus in the overlay.
        -   Arrow key navigation: Up & Left - Back 1 picture
                                  Down & Right - Forward 1 picture
                                  
    
    This "software" is released to you as an open source learning tool. Please do not
    reuse this code without this comment block in it. Also, please keep this software
    open source. Don't be a codehog.
    
    This "software" contains the license: Creative Commons - Attribution-Share Alike 3.0
    Unported (http://creativecommons.org/licenses/by-sa/3.0/).

-->
<?php

    $photosDir = "./";

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Pictures</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
        
        <style type="text/css">
            * {
                font-family:"Trebuchet MS";
                font-size:10pt;
                color:#555;
            }
            body {
                min-width:800px;
                margin:0px;
                padding:20px;
            }
            div.container {
                background:#EEE;
                border:1px solid #AAA;
            }
            div.header {
                background:#CCC;
                height:20px;
                font-weight:bold;
                border-bottom:1px solid #888;
                padding-top:2px;
                padding-left:10px;
                padding-right:10px;
            }
            div.header a { text-decoration:none; }
            div.header a:hover {
                text-decoration:underline;
            }
            div.content {
                padding-top:5px;
                padding-bottom:5px;
                padding-left:10px;
                padding-right:10px;
            }
            div.content a { text-decoration:none; }
            div.content a:hover { text-decoration:underline; }
            div#blind {
                background:#EEE;
                width:100%;
                height:100%;
                display:none;
                position:absolute;
                top:0px;
                left:0px;
                z-index:9999;
            }
            div#lights_down {
                background:black;
                opacity:0.9;
                filter:alpha(opacity=90);
                display:none;
                width:100%;
                height:100%;
                position:absolute;
                top:0px;
                left:0px;
                z-index:499;
            }
            div#lights_down a { color:white; }
            div#photos {
                margin:auto;
                min-height:100px;
            }
            div#photos div.content {
                text-align:center;
            }
            div#photos img {
                max-width:650px;
                max-height:500px;
                margin:auto;
                border:1px solid #333;
            }
            div#settings {
                background:#CCC;
                font-size:9pt;
                font-weight:normal;
                text-align:right;
                border:1px solid #AAA;
                border-top:1px solid #AAA;
                border-bottom:1px solid #888;
                padding:10px;
                padding-top:5px;
                padding-bottom:5px;
                display:none;
                z-index:501;
            }
            div#settings input { font-weight:normal; font-size:9pt; }
            div#info_tooltip {
                background:#CCC;
                border:1px solid #AAA;
                border-right:1px solid #888;
                border-bottom:1px solid #888;
                padding:5px;
                display:none;
                position:absolute;
                top:0px;
                left:0px;
                z-index:502;
            }
            div#info_tooltip table tr td { padding-left:2px; padding-right:2px; }
            div#thumbnails {
                width:125px;
                height:520px;
                padding-left:5px;
                overflow-y:scroll;
                overflow-x:hidden;
            }
            div#thumbnails table tr td {
                padding-bottom:3px;
                padding-top:3px;
            }
            div#thumbnails img {
                max-width:100px;
                max-height:100px;
                border:1px solid #AAA;
                opacity:0.55;
                filter:alpha(opacity=55);
            }
            div#thumbnails img:hover, div#thumbnails img.active {
                opacity:1;
                filter:alpha(opacity=100);
                border:1px solid #333;
                cursor:default;
            }
            td#pContainer {
                padding-left:3px;
            }
            td#pContainer img {
                position:relative;
                z-index:500;
            }
        </style>
        
        <?php
        
            $files = scandir($photosDir);
            
            foreach ($files as $key=>$file) {
                if (preg_match("/(.png|.ico|.gif|.jpg|.jpeg)$/",$file)) {
                    $imgs[] = $file;
                }
            }
            
            foreach ($imgs as $key=>$img) {
                $fimg = $photosDir.$img;
                $size = filesize($fimg);
                $x = 0;
                $y = array('B','KB','MB','GB','TB');
                do {
                    $size = round(($size / 1024),2);
                    $x++;
                }
                while ($size >= 1024);
                $size.=" {$y[$x]}";
                $reso = getimagesize($fimg);
                $tmp = array("'$key'","'$fimg'","'$img'","'$size'","'{$reso[0]}'","'{$reso[1]}'");
                $tmp = implode(',',$tmp);
                $jsOut[] = "[$tmp]";
            }
            
            $jsOut = implode(',',$jsOut);
            echo "<script type=\"text/javascript\">var photos = [$jsOut];</script>";
        
        ?>
        <script type="text/javascript">

            var preload_images = 10;     // How many images to pre-load at one time.
            var next_preload = 7;       // Images left before preloading the set preload_images amount.
            var thumb_count = 0;
            var last_id = -1;
            var slideshow = false;
            var slideshow_speed = 3000;
            var lights_down = true;
            var settings = false;
            var settings_focused = false;
            var blind = false;
            var keys = 0;
            var wait = false;
            
            function ajax_get(url) {
                $.ajax({
                    url: url,
                    method: 'GET',
                    success: function (html) { return html; },
                    error: function () { return false; }
                });
            }

            function switchPicture(id) {
                if (photos[id] != null) {
                    id = parseInt(id);
                    if (id != last_id) {
                        $('#info_tooltip').css('display','none');
                        $('img').each(function() { if($(this).attr('id').substr(0, 3) == 'img') { $(this).hide('500'); } });
                        $('#img_'+id).show('500', function() {
                            $('.active').removeClass('active');
                            $('#img_'+id).css('display','inline');
                            $('#thumb_'+id).addClass('active');
                            var scrollTo = 0;
                            for (i=0;i<id-1;i++) { scrollTo += ($('#thumb_'+i).height() + 8); }
                            $('#thumbnails').scrollTop(scrollTo);
                            last_id = id;
                        });
                        $('a.thumb_link').each(function() { $(this).blur(); });
                        if ((id+1) >= (thumb_count - next_preload)) {
                            cut = thumb_count+(preload_images-1);
                            for (i=thumb_count;i<=cut;i++) {
                                regex = /(.png|.gif|.ico|.jpg|.jpeg)$/
                                if (photos[i]!=null&&regex.exec(photos[i][1])!=null) {
                                    ptmp = ajax_get(photos[i][1]);
                                    if (ptmp != false) {
                                        $('div#thumbnails table').append('<tr><td align="center"><a href="#'+(i+1)+'" class="thumb_link" onclick="switchPicture(\''+i+'\')" onmousemove="toggle_tooltip(event,\''+i+'\',true)" onmouseout="toggle_tooltip(event,\''+i+'\',false)"><img src="'+photos[i][1]+'" alt="'+photos[i][1]+'" id="thumb_'+photos[i][0]+'" /></a></td></tr>');
                                        $('td#pContainer').append('<a href="'+photos[i][1]+'" target="_blank"><img src="'+photos[i][1]+'" alt="'+photos[i][1]+'" id="img_'+photos[i][0]+'" onmousemove="toggle_tooltip(event,\''+i+'\',true)" onmouseout="toggle_tooltip(event,\''+i+'\',false)" style="display:none" /></a>');
                                        thumb_count++;
                                    }
                                } else {delete(photos[i]);if((cut+1)<=photos.length)cut++;}
                            }
                        }
                    }
                }
            }
            
            function urlParse() {
                tmp = window.location.href;
                if (tmp.indexOf('#') == -1) tmp=0;
                else tmp = tmp.substr(tmp.indexOf('#')+1);
                return parseInt(tmp);
            }
            
            function validate_key(e,type) {
                key = (window.event) ? event.keyCode : e.keyCode;
                if (key==8||key==13) return true;
                switch (type) {
                    case 'num':
                        if ((key>=48&&key<=57)||(key==190)) return true;
                        break;
                    case 'alpha':
                        if ((key>=57&&key<=90)) return true;
                        break;
                    case 'alphanum':
                        if ((key>=48&&key<=90)) return true;
                        break;
                }
                return false;
            }
            
            function toggle_slideshow() {
                if (slideshow==false) {
                    slideshow=true;
                    slideTimer = setTimeout('next_slide()',slideshow_speed);
                    if (lights_down==true) { $('#lights_down').show('500',function(){$(this).html('<span style="float:right; margin-top:10px; margin-right:10px;"><a href="javascript:toggle_slideshow();">Stop Slideshow</a></span>');}); }
                    else { $('#toggle_slideshow').text('Stop Slideshow'); }
                }
                else {
                    slideTimer=null; slideshow=false;
                    $('#lights_down').hide('500',function(){$(this).html('');});
                    $('#toggle_slideshow').text('Start Slideshow');
                }
                $('#toggle_slideshow').blur();
            }
            function next_slide() {
                if (slideshow) {
                    if (last_id >= (photos.length-1)) last_id=-1;
                    $('#info_tooltip').css('display','none');
                    switchPicture(last_id+1); slideTimer=setTimeout('next_slide()',slideshow_speed);
                }
            }
            function toggle_settings() {
                link_pos = $('#settings_link').position();
                $('#settings').css({
                    position: 'absolute',
                    right: (($(document).width()-link_pos.left)-$('#settings_link').width())+"px",
                    top: (link_pos.top+20)+"px"
                });
                settings=!settings;
                if (settings) $('#settings').fadeIn('500'); else $('#settings').fadeOut('500');
            }
            function toggle_blind() { $('#blind').toggle('500',function() { blind = !blind; }); $('a#toggle_blind').blur(); }
            function toggle_google() {$('#google').toggle('500',function() {if ($(this).attr('src')==undefined)$(this).attr('src','http://google.com');$('a#toggle_google').blur();});}
            var tool_focused=false;
            var toolTimer=null;
            function toggle_tooltip(e,i,f) {
                if (f==true) {
                    tool_focused=true;
                    $('#info_tooltip').css({
                        position:'absolute',
                        top:(e.pageY+20)+"px",
                        left:(e.pageX+10)+"px"
                    });
                    if ($('#info_tooltip').attr('display')!='block') {
                        $('#info_tooltip').fadeIn('500');
                        $('#filename','#info_tooltip').html(photos[i][2]);
                        $('#filesize','#info_tooltip').html(photos[i][3]);
                        $('#resolution','#info_tooltip').html(photos[i][4]+'x'+photos[i][5]);
                    }
                    clearTimeout('toolTimer');
                    toolTimer=setTimeout('tool_focused=false',1000);
                }
                else {
                    $('#info_tooltip').css('display','none');
                }
            }
            
            $(document).ready(function() {
                cut = (urlParse()>=preload_images) ? urlParse()+preload_images : preload_images;
                for (i=0;i<=cut-1;i++) {
                    if (photos[i] != null) {
                        regex = /(.png|.gif|.ico|.jpg|.jpeg)$/
                        if (photos[i]!=null&&regex.exec(photos[i][1])!=null) {
                            ptmp = ajax_get(photos[i][1]);
                            if (ptmp != false) {
                                $('div#thumbnails table').append('<tr><td align="center"><a href="#'+(i+1)+'" class="thumb_link" onclick="switchPicture(\''+i+'\')" onmousemove="toggle_tooltip(event,\''+i+'\',true)" onmouseout="toggle_tooltip(event,\''+i+'\',false)"><img src="'+photos[i][1]+'" alt="'+photos[i][1]+'" id="thumb_'+photos[i][0]+'" /></a></td></tr>');
                                $('td#pContainer').append('<a href="'+photos[i][1]+'" target="_blank"><img src="'+photos[i][1]+'" alt="'+photos[i][1]+'" id="img_'+photos[i][0]+'" onmousemove="toggle_tooltip(event,\''+i+'\',true)" onmouseout="toggle_tooltip(event,\''+i+'\',false)" style="display:none" /></a>');
                                thumb_count++;
                            }
                        } else {delete(photos[i]);if((cut+1)<=photos.length)cut++;}
                    }
                }
                if (urlParse()>0) switchPicture(urlParse()-1);
                else if (last_id == -1) switchPicture(0);
                $(document).keydown(function(e) {
                    key = (window.event) ? event.keyCode : e.keyCode;
                    if (key == "13") {
                        keys += key;
                        if (keys == 26) { toggle_blind(); keys = 0; }
                    }
                    else if (wait!=true&&slideshow!=true) {
                        if (key == "37" || key == "38") { switchPicture(last_id - 1); wait=true; var waitTimer=setTimeout('wait=false',1000); }
                        else if (key == "39" || key == "40") { switchPicture(last_id + 1); wait=true; var waitTimer=setTimeout('wait=false',1000); }
                    }
                    else {
                        if (window.event)event.preventDefault();
                        else e.preventDefault();
                    }
                });
                $(document).click(function() { if (settings==true&&settings_focused==false) toggle_settings(); });
                $(document).mousemove(function() { if (tool_focused==false) $('#info_tooltip').css('display','none'); });
                $('#settings,#settings_link').bind({
                    mouseover: function() {settings_focused=true;},
                    mouseout: function() {settings_focused=false;}
                });
                $(window).resize(function() {
                    $('#blind').height($(document).height()); $('#lights_down').height($(document).height());
                    link_pos=$('#settings_link').position();
                    $('#settings').css({
                        position: 'absolute',
                        right: (($(document).width()-link_pos.left)-$('#settings_link').width())+"px",
                        top: (link_pos.top+20)+"px"
                    });
                });
                if (($('#slideshow_speed').val()*1000)!=slideshow_speed) slideshow_speed=$('#slideshow_speed').val()*1000;
                if ($('#lights_down').is(':checked')) lights_down=false; else lights_down=true;
            });
            
       </script>
    </head>
    <body>
        <div id="blind">
            <table cellspacing="0" cellpadding="0" border="0" width="100%" height="100%">
                <tr>
                    <td align="center" valign="middle" height="40px">
                        <a id="toggle_google" href="javascript:toggle_google()">Google</a><br />
                        <a id="toggle_blind" href="javascript:toggle_blind()" style="font-size:8pt;">Remove Blind</a>
                    </td>
                </tr>
                <tr>
                    <td align="center" valign="bottom"><iframe id="google" width="100%" height="99%" style="border:0px; border-top:1px solid #AAA; display:none;"></iframe></td>
                </tr>
            </table>
        </div>
        <div id="lights_down"></div>
        <div id="photos" class="container">
            <div class="header">Photos
                <span style="float:right">
                    <a id="toggle_slideshow" href="javascript:toggle_slideshow()">Start Slideshow</a> | <a id="settings_link" href="javascript:toggle_settings()">Settings</a>
                    <div id="settings">
                        Slideshow Speed:
                        <input id="slideshow_speed" type="text" onkeydown="return validate_key(event,'num')" onchange="if ($(this).val()=='') { $(this).val('3'); } slideshow_speed=$(this).val()*1000;" style="height:20px; width:30px; text-align:center;" value="3" /> seconds<br />
                        <input id="lights_down" type="checkbox" onchange="lights_down=!lights_down" />
                        Disable "Theater" Mode
                    </div>
                </span>
            </div>
            <div class="content">
                <div id="info_tooltip">
                    <table cellpadding="0" cellspacing="0" border="0" width="100%">
                        <tr><td align="right"><b>Filename:</b></td><td id="filename"></td></tr>
                        <tr><td align="right"><b>Filesize:</b></td><td id="filesize"></td></tr>
                        <tr><td align="right"><b>Resolution:</b></td><td id="resolution"></td></tr>
                    </table>
                </div>
                <table cellpadding="0" cellspacing="0" border="0" width="100%">
                    <tr>
                        <td width="150px">
                            <div id="thumbnails">
                                <table cellpadding="0" cellspacing="0" border="0">
                                </table>
                            </div>
                        </td>
                        <td align="center" valign="middle" id="pContainer"></td>
                    </tr>
                </table>
            </div>
        </div>
        <div style="text-align:center; margin-top:10px;">
            <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-sa/3.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0 Unported License</a>.
        </div>
    </body>
</html>

Edit: Woot. It worked.
for what is this? Big Grin