Saturday 5 October 2013

Create Dynamic Image Gallery Slideshow using ASP.NET and jQuery Lightbox

9 comments
In my previous post, I've explained how to upload multiple files using ASP.NET 4.5 . In this post, I am going to explain how to create dynamic image gallery using ASP.NET 4.5 and jQuery. The user uploads multiple images at once and those images will be added to a photo gallery or album. As part of uploading image process, we need to store original images on website’s uploads folder. At the same time, we also need to create thumbnail of images. We can divide complete functionality in below three processes:
  1. User uploads multiples images to create a new photo gallery. Store gallery details into database.
  2. Create thumbnail for uploaded images.
  3. Display gallery using jQuery colorbox plugin to get lightbox effect.

Upload multiple images and create gallery

First of all create table tblGallery into database to implement slideshow functionality. SQL Scripts can be downloaded from GitHub.

Column NameData Type
GalleryIdint (set identity property=true)
GalleryNamevarchar(50)
GalleryDescriptionvarchar(500)
GalleryCreatedDatedatetime
Create a new webform CreateAlbum.aspx and write following code in .aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CreateAlbum.aspx.cs" Inherits="CreateAlbum" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Create Album</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Enter Gallery Name
                    </td>
                    <td>
                        <asp:TextBox ID="txtGalleryName" runat="server" Width="90%" MaxLength="100">
                        </asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:RequiredFieldValidator ID="rfvtxtGalleryName" runat="server" ErrorMessage="Enter Gallery Name"
                            ForeColor="Red" ControlToValidate="txtGalleryName">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>Enter Gallery Description
                    </td>
                    <td>
                        <asp:TextBox ID="txtGalleryDescrption" runat="server" TextMode="MultiLine" Width="90%"
                            Height="50px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:RequiredFieldValidator ID="rfvtxtGalleryDescrption" runat="server" ErrorMessage="Enter Gallery Description"
                            ForeColor="Red" ControlToValidate="txtGalleryDescrption">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>Upload Photos to Album</td>
                    <td>
                        <asp:FileUpload AllowMultiple="true" ID="MultipleFileUpload" runat="server"></asp:FileUpload></td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:RequiredFieldValidator ID="rfvFileUploadGallery" runat="server" ErrorMessage="Upload Gallery Photos"
                            ForeColor="Red" ControlToValidate="MultipleFileUpload">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
This webform has two textbox to enter Gallery Name and Gallery description respectively, one file upload control to upload multiple files and one button to submit the data. After completion on .aspx page, write below code on button click event handler in code behind page CreateAlbum.aspx.cs:
protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            if (MultipleFileUpload.HasFiles)
            {
                int MaxGalleryId, ReturnValue;
                ReturnValue = obj.fnCreateNewPhotoGallery(txtGalleryName.Text, txtGalleryDescrption.Text, DateTime.Now, out MaxGalleryId);
                if (ReturnValue != 0)
                {
                    string GalleryPath = System.Configuration.ConfigurationManager.AppSettings["GalleryPath"] + MaxGalleryId;
                    Directory.CreateDirectory(Server.MapPath(GalleryPath));

                    string ThumbnailPath = System.Configuration.ConfigurationManager.AppSettings["ThumbnailPath"] + MaxGalleryId;
                    Directory.CreateDirectory(Server.MapPath(ThumbnailPath));

                    StringBuilder UploadedFileNames = new StringBuilder();

                    foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
                    {
                        //Upload file
                        string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
                        string SaveAsImage = System.IO.Path.Combine(Server.MapPath(GalleryPath + "/"), FileName);
                        uploadedFile.SaveAs(SaveAsImage);

                        //Create thumbnail for uploaded file and save thumbnail on disk
                        Bitmap Thumbnail = CreateThumbnail(SaveAsImage, 200, 200);
                        string SaveAsThumbnail = System.IO.Path.Combine(Server.MapPath(ThumbnailPath + "/"), FileName);
                        Thumbnail.Save(SaveAsThumbnail);
                    }
                    HTMLHelper.jsAlertAndRedirect(this, "Gallery created successfully. ", "Album.aspx?GalleryId=" + MaxGalleryId);
                }
            }
        }

        catch
        {
            HTMLHelper.jsAlertAndRedirect(this, "Gallery is not created. Some exception occured ", "CreateAlbum.aspx");
        }
    }
On button click, I am saving gallery details into database table tblGallery and saving images into website’s uploads folder. In the mean time I am also creating thumbnail for image. Refer next section for thumbnail creation.

Creating thumbnail

I've created a function CreateThumbnail which converts given image into thumbnail form. This function accepts below three parameters and returns a bitmap image of the changed thumbnail image which we can save on the disk.
  1. ImagePath : Path of original image
  2. ThumbnailWidth : Required width for thumbnail
  3. ThumbnailHeight : Required height for thumbnail
/// <summary>
    /// CreateThumbnail function returns a Bitmap image of the changed thumbnail image which we can save on the disk.
    /// </summary>
    public Bitmap CreateThumbnail(string ImagePath, int ThumbnailWidth, int ThumbnailHeight)
    {
        System.Drawing.Bitmap Thumbnail = null;
        try
        {
            Bitmap ImageBMP = new Bitmap(ImagePath);
            ImageFormat loFormat = ImageBMP.RawFormat;

            decimal lengthRatio;
            int ThumbnailNewWidth = 0;
            int ThumbnailNewHeight = 0;
            decimal ThumbnailRatioWidth;
            decimal ThumbnailRatioHeight;

            // If the uploaded image is smaller than a thumbnail size the just return it
            if (ImageBMP.Width <= ThumbnailWidth && ImageBMP.Height <= ThumbnailHeight)
                return ImageBMP;

            // Compute best ratio to scale entire image based on larger dimension.
            if (ImageBMP.Width > ImageBMP.Height)
            {
                ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
                ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
                lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
                ThumbnailNewWidth = ThumbnailWidth;
                decimal lengthTemp = ImageBMP.Height * lengthRatio;
                ThumbnailNewHeight = (int)lengthTemp;
            }
            else
            {
                ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
                ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
                lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
                ThumbnailNewHeight = ThumbnailHeight;
                decimal lengthTemp = ImageBMP.Width * lengthRatio;
                ThumbnailNewWidth = (int)lengthTemp;
            }
            Thumbnail = new Bitmap(ThumbnailNewWidth, ThumbnailNewHeight);
            Graphics g = Graphics.FromImage(Thumbnail);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.FillRectangle(Brushes.White, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);
            g.DrawImage(ImageBMP, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);

            ImageBMP.Dispose();
        }
        catch
        {
            return null;
        }

        return Thumbnail;
    }

Display gallery using jQuery colorbox plugin

Create new webform Album.aspx to display gallery slideshow using jQuery colorbox plugin. Write following code in .aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Album.aspx.cs" Inherits="Album" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>View Gallery</title>
    <script src="js/jquery-1.8.js" type="text/javascript"> </script>
    <script src="js/jquery.colorbox.js" type="text/javascript"></script>
    <script>
        $(document).ready(function () {
            //Examples of how to assign the ColorBox event to elements
            $(".group1").colorbox({ rel: 'group1', transition: "fade", slideshow: "true" });
        });
    </script>
    <link rel="stylesheet" href="css/colorbox.css" />
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h1><%= GalleryName %></h1>
            <h2><%= GalleryDescription %></h2>
            <asp:DataList ID="dlGallery" runat="server" RepeatColumns="4" RepeatDirection="Horizontal"
                Width="100%">
                <ItemTemplate>
                    <table border="1">
                        <tr>
                            <td>
                                <a href='<%#Eval("GalleryImagePath") %>' class='group1' title='<%= GalleryName %> : <%= GalleryDescription %>'>
                                    <img src='<%#Eval("ThumbnailImagePath") %>' alt='' />
                                </a>
                            </td>
                        </tr>
                        <br />
                    </table>
                </ItemTemplate>
            </asp:DataList>
        </div>
    </form>
</body>
</html>
In above code, I am binding gallery data into datalist and display it using jQuery colorbox plugin.  I’ve added few scripts and css file references in header section of above code. Using these files we can get lightbox slideshow effect.  These files are included in sample code. You can download sample code from GitHub. Another important thing to be noticed is href link tag.
<a href='<%#Eval("GalleryImagePath") %>' class='group1' rel='group1' title='<%= GalleryName %> : <%= GalleryDescription %>'>
<img src='<%#Eval("ThumbnailImagePath") %>' alt='' />
</a>
  • href='<%#Eval("GalleryImagePath") %>' : This will have image path.  
  • rel='group1' : This allows to group any combination of elements together for a gallery.
  • title='<%= GalleryName %> : <%= GalleryDescription %>' : This attribute is used to display image caption.
On page load following jQuery script is getting executed to assign Colorbox events to elements. For detail documentation about Colorbox plugin check their official page.
<script>
        $(document).ready(function () {
            //Examples of how to assign the ColorBox event to elements
            $(".group1").colorbox({ rel: 'group1', transition: "fade", slideshow: "true" });
        });
</script>
Complete source code and SQL scripts of this tutorial can be downloaded from GitHub. Source code mainly contains three webforms:
  1. CreateAlbum.aspx : To upload images and create gallery.
  2. AlbumList.aspx : To view complete list of created galleries.
  3. Album.aspx : To display images of a specific gallery using lightbox effect.
Please note that this is basic tutorial to create dynamic image gallery slideshow using ASP.NET and jQuery Lightbox. New functionalities like Cover Image for every gallery or different title for every image can be added.
Comments and suggestions are most welcome. Happy coding!

9 comments :