Saturday 3 May 2014

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

In this post, I am going to explain how to create dynamic image gallery using ASP.NET 4.0 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  Here.
Create database Album

use Album
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[tblGallery](
      [GalleryId] [int] IDENTITY(1,1) NOT NULL,
      [GalleryName] [varchar](50) NOT NULL,
      [GalleryDescription] [varchar](500) NOT NULL,
      [GalleryCreatedDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED
(
      [GalleryId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


--
CREATE PROCEDURE [dbo].[usp_CreateNewGallery]
      -- Add the parameters for the stored procedure here
      (
      @GalleryName varchar(50),
      @GalleryDescription varchar(500),
      @GalleryCreatedDate datetime,
      @MaxGalleryId int output
      )
AS
BEGIN
     
      insert into tblGallery values (@GalleryName,@GalleryDescription,@GalleryCreatedDate)
      Select @MaxGalleryId= MAX(GalleryId)from tblGallery
     
END

GO

CreateAlbum.aspx Source Code :

<%@ 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 Multiple="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>


CreateAlbum.aspx Code Behind:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class CreateAlbum : System.Web.UI.Page
{
    Logic obj = new Logic();
    string FileName;
    string error;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            if (MultipleFileUpload.HasFile)
            {
                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();

                     HttpFileCollection hfc = Request.Files;
                     for (int i = 0; i < hfc.Count; i++)
                     {
                         HttpPostedFile hpf = hfc[i];
                         FileName = System.IO.Path.GetFileName(hpf.FileName);
                         if (hpf.ContentLength > 0)
                         {
                             if (hpf.ContentLength < 5307200)
                             {
                                
                                 string Ext = System.IO.Path.GetExtension(hpf.FileName);
                                 if ((Ext == ".png") || (Ext == ".jpg") || (Ext == ".jpeg") || (Ext == ".bmp") || (Ext == ".gif"))
                                 {
                                     String UploadedFile = hpf.FileName;
                                     int ExtractPos = UploadedFile.LastIndexOf("\\") + 1;

                                     //to retrieve only Filename from the complete path
                                     String UploadedFileName = DateTime.Now.ToString("ddMMyyhhmmss") + UploadedFile.Substring(ExtractPos, UploadedFile.Length - ExtractPos);
                                     string SaveAsImage = System.IO.Path.Combine(Server.MapPath(GalleryPath + "/"), UploadedFileName);

                                     hpf.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 + "/"), UploadedFileName);
                                     Thumbnail.Save(SaveAsThumbnail);
                                 }
                                 else
                                 {
                                     error = "'" + FileName.ToString() + "'" + " Failed :" + "'" + Ext.ToString() + "'" + " Extension not supported... " + "";
                                 }
                             }
                             else
                             {
                                 error = "'" + FileName.ToString() + "'" + " Failed : " + " file length should not exceed 3MB... " + "";
                             }
                         }
                         else
                         {
                             error = "'" + FileName.ToString() + "'" + " Failed : " + " File is Empty... " + "";
                         }
                     }

                    HTMLHelper.jsAlertAndRedirect(this, "Gallery created successfully. ", "Album.aspx?GalleryId=" + MaxGalleryId);
                }
            }
        }

        catch
        {
            HTMLHelper.jsAlertAndRedirect(this, "Gallery is not created. Some exception occured ", "CreateAlbum.aspx");
        }
    }

    /// <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' rel='group1' title='<%= GalleryName %> : <%= GalleryDescription %>'>
                                    <img src='<%#Eval("ThumbnailImagePath") %>' alt='' />
                                </a>
                            </td>
                        </tr>
                        <br />
                    </table>
                </ItemTemplate>
            </asp:DataList>
        </div>
    </form>
</body>
</html>


  • 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.
  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.

Download Here




No comments:

Post a Comment