May 25 2007

A simple image gallery

Posted by admin under Ajax

I have gotten a lot of questions on how I have implemented the "lightbox" screenshots viewer at AdMentor.net. To see what I mean just go to AdMentor.net, scroll down to the bottom (Some screenshots) and click on one of the images.

It starts a slideshow and you can click on next/prev to browse through all images. This is neither a new nor a unique solution - I would say there are at least ten different javascript implementations of this "lightbox" stuff, but I will show you how you can implement it in just a few lines in ASP.NET.

First - I use JQuery as my base javascript framework. Next to get the lightbox stuff I use the JQuery plugins Imagebox (IUtil.js is also needed) from Interface

The downloadable solution contains all the files you need but I will show you here what it looks like: 

 

Now the idea is to put the images inside the pics directory and our script  should

a) automatically create thumnbails

b) hook up the lightbox so when the user clicks on a image the lightbox will start up

So, lets start with thumbnail. I have added my "standard" createthumbnail.ashx handler to the project and basically you call it like this

<img src="/createthumb.ashx?gu=/pics/pic1.jpg&xmax=100&ymax=100"> and it then tries to create a thumbnail of the file /pics/pic1.jog with the maximum size as specified by xmax and ymax. The handler tries to preserve width and height relation.

So lets jump over to the default.aspx file:



<head runat="server">
    <title>Untitled Page</title>
    <script src="jquery/jquery-113.pack.js" type="text/javascript"></script>
    <script src="jquery/imagebox/iutil.js" type="text/javascript"></script>
    <script src="jquery/imagebox/imagebox.js" type="text/javascript"></script>
    <link href="jquery/imagebox/imagebox.css" rel="stylesheet" />
    <script type="text/javascript">
        $(document).ready(function()
            {
                $.ImageBox.init
                    (
                        {
                            loaderSRC:'/jquery/imagebox/loading.gif',
                            closeHTML:'<img src="/jquery/imagebox/close.jpg" />'
                        }
                    );
            }
    );    
</script>
</head>


Basically we are just including the needed javascript files and as you can see we are calling a function called ImageBox.init which, thats right, initializes the imagebox.

Now we just need to get the files displayed in the was the imagebox wants it:

Here's the body of the default.aspx file:



<body>
    <form id="form1" runat="server">
    <div>
    <h1>A simple gallery</h1>
    <asp:Repeater ID="repImages" runat="server" OnItemDataBound="repImages_ItemDataBound">
    <HeaderTemplate><p></HeaderTemplate>
    <ItemTemplate>
        <asp:HyperLink ID="hlWhat" runat="server" rel="imagebox-bw">
        <asp:Image ID="imgTheImage" runat="server" />
        </asp:HyperLink>
    </ItemTemplate>
    <FooterTemplate></p></FooterTemplate>
    </asp:Repeater>
    </div>
    </form>
</body>



The big "secret" is that we specify rel="imagebox-bw" for the hyperlink - that way ImageBox.init will be able to hook it up into the lighbox.

Now the codebehind:



        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string sBasePath = System.Web.HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"];
                if ( sBasePath.EndsWith("\\"))
                    sBasePath = sBasePath.Substring(0,sBasePath.Length-1);

                sBasePath = sBasePath + "\\" + "pics";

                System.Collections.Generic.List<string> oList = new System.Collections.Generic.List<string>();
                foreach (string s in System.IO.Directory.GetFiles(sBasePath, "*.*"))
                {
                    //We could do some filtering for example only adding .jpg or something
                    oList.Add( System.IO.Path.GetFileName( s ));

                }
                repImages.DataSource = oList;
                repImages.DataBind();
            }

        }


Not too much to write home about here. We just loop through the pics directory and adds all images to a list - which we use as the datasource for the repeater. In repeater.databind the code looks like this:



        protected void repImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem ||
                e.Item.ItemType == ListItemType.Item)
            {
                string sFile = e.Item.DataItem as string;

                //Create the thumblink
                HyperLink hlWhat = e.Item.FindControl("hlWhat") as HyperLink;
                hlWhat.NavigateUrl = ResolveUrl("~/pics/" + sFile  );
                hlWhat.ToolTip = System.IO.Path.GetFileNameWithoutExtension(sFile);
                hlWhat.Attributes["rel"] = "imagebox-bw";

                Image oImg = e.Item.FindControl("imgTheImage") as Image;
                oImg.ImageUrl = ResolveUrl("~/createthumb.ashx?gu=/pics/" + sFile + "&xmax=100&ymax=100" );


            }

        }


Now just download the zip file and have a go at it. This is a very "raw" solution I admit, but with some thinking I bet you can implement some reusable control and/or patterns out of it.

 

Attachments