Click here to Skip to main content
13,769,395 members
Click here to Skip to main content
Add your own
alternative version


85 bookmarked
Posted 16 Dec 2008
Licenced CPOL

AJAX Photo Album Project

, 16 Dec 2008
Rate this:
Please Sign up or sign in to vote.
The project shows how to create a photo album and slideshow using AJAX XmlHttpRequest.



This article describes several techniques on how to create a simple photo album and slideshow:

  • Save and retrieve images from a MS SQL Server database
  • Resize images
  • Retrieve images from the database using AJAX XmlHttpRequest
  • Use the AJAX UpdatePanel and ScriptManager to retrieve images from a database without refreshing the web page


The AjaxPhotoAlbum project was developed to show several useful techniques:

  1. The sample photo album consists of thumbnails and an image control to browse the large image.
  2. When the user moves mouse over a thumbnail image, the large image also gets populated with the selected image. The large image is retrieved from the database with the AJAX XmlHttpRequest using the web page GetSelectedImage.aspx.

  3. The user can also click "Previous" (<<) and "Next" (>>) link buttons to get the previous / next image in a large image placeholder. The whole control is placed inside an AJAX UpdatePanel, and because of that, even if the images are retrieved from the database on postback events, the web page does not get refreshed, and only the large image control gets updated with the new image.
  4. The user can also run the slide show that will retrieve images from the database in an interval selected from an Interval drop down list control. In this case, an AJAX XmlHttpRequst object is used to send requests and get the responses using the web page behind GetSelectedImage.aspx.
  5. The images for the photo album are stored in a database. To add an image to a database, the user can click the "Add New Image" button. The original image is resized to two different sizes - small (120 px width - used for thumbnails) and large (250 px width - used for the large image placeholder) and saved to the "Images" table in a database.
  6. When an image is required to be retrieved from the database (either for a thumbnail or large image control), it is read into a byte array and then is written to the web page "ImagePage.aspx", the link to which in turn is used as "src" attribute of the image control on a web page.

Using the code

For this project, an MS SQL Server database "AjaxPhotoAlbum" with just one table "Images" was created. The script to create the table can be found in the download package, but below is the description of the "Images" table:

Column NameData Type
ImageIdint (PK, Identity Seed = 1)

This table will hold the images for the AjaxPhotoAlbum project. The connection string from the web.config file is shown here:

    <add key="DSN" 

      value="server=localhost;Integrated Security=SSPI;database=AjaxPhotoAlbum"/>

The complete project structure includes four layers:

  • Presentation Layer: Default.aspx
    • GetSelectedImage.aspx (the web page that provides actual post backs in AJAX XmlHttpRequest calls)
    • ImagePage.aspx (the web page that presents the image retrieved from the database in an image control)
    • WebControls:
      • PhotoAlbumControl.ascx
      • SlideShow.ascx
    • JavaScript
      • AjaxImage.js
    • Images
    • CSS
  • Business Layer: App_Code
  • BL

    • ImageClass.cs
  • Data Access Layer: App_Code
  • DAL

    • SQLHelper.cs
  • MS SQL Server database: The AjaxPhotoAlbum database
    • Images table

PhotoAlbumControl.ascx is placed on the Default.aspx web page inside an AJAX UpdatePanel. Default.aspx also has a ScriptManager control. In order to make AJAX controls work, it is necessary to have the <httpHandlers> section under <system.web> node.

    <remove verb="*" path="*.asmx"/>
    <add verb="*" path="*.asmx" validate="false" 

            System.Web.Extensions, Version=1.0.61025.0, 
            Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    <add verb="*" path="*_AppService.axd" 


                  System.Web.Extensions, Version=1.0.61025.0, 
                  Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    <add verb="GET,HEAD" path="ScriptResource.axd" 

                   System.Web.Extensions, Version=1.0.61025.0, 
                   Culture=neutral, PublicKeyToken=31bf3856ad364e35" 


With the above, when the user clicks "Previous" /"Next" buttons ("<<" or ">>"), the web page is posted back but is not refreshed as a whole. Only the imgPhoto web control is refreshed with the new selected image. The thumbnails are built as a DataList control. The images IDs are retrieved from the database, and on the DataList ItemDataBound() event, the thumbnail images attribute "src", "onclick", and "onmouseover" - are being populated.

protected void ThumbnailsItemDatabound(object sender, DataListItemEventArgs e)
    Image tImage = (Image)dlThumbnails.Controls[e.Item.ItemIndex].Controls[3];
    string ajaxServerUrl = "GetSelectedImage.aspx";
    tImage.Attributes.Add("src", "ImagePage.aspx?s=s&id=" + 
      "getImage(‘" + ajaxServerUrl + "‘," + 
      ((DataRowView)e.Item.DataItem).Row.ItemArray[0].ToString() + ")");
    tImage.Attributes.Add("onmouseover", "getImage(‘" + 
      ajaxServerUrl + "‘," + 
      ((DataRowView)e.Item.DataItem).Row.ItemArray[0].ToString() + ")");

The "onclick" and "onmouseover" thumbnail image attributes are called in the AJAX JavaScript function getImage() to populate the large image control impPhoto with the image selected in the thumbnails. The getImage() JavaScript function sends the AJAX XmlHttpRequest to the web page GetSelectedImage.aspx, which in turns does the actual postback to retrieve the requested image ID from the database.

//Sending information to server
function getImage(AjaxServerUrl, id)
    var url = AjaxServerUrl + "?id=" + id"GET", url);
    imageClient.onreadystatechange = getImageBack; 

The GetSelectedImage.aspx web page retrieves the required image ID and returns it as a response in XML format.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Tirex;
public partial class GetSelectedImage : System.Web.UI.Page
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
        Response.ContentType = "text/xml";
        int id = 0;
        if (Request.Params["id"] != null)
            id = Int32.Parse(Request.Params["id"].ToString());
            if (Session["ImageId"] != null)
                id = Int32.Parse(Session["ImageId"].ToString());
            id = ImageClass.GetImageId(id);
            Session["ImageId"] = id.ToString();
        Session["SelectedImageId"] = id.ToString();

The response is in turn received and parsed by the getImageBack() JavaScript function. Please, consider the differences on how the response is processed for Internet Explorer and Firefox.

//Waiting and processing server response
function getImageBack(response)
    var imageId = 0;
        if(imageClient.readyState == COMPLETE && imageClient.status == OK)
            //branch for Firefox version
            if (document.implementation.createDocument)//Firefox
                //Get Image
                var xmlElementImageId = 
                imageId = xmlElementImageId.textContent;
            //branch for IE/Windows ActiveX version
            else if (document.all)//IE
                xmlDocument = new ActiveXObject(‘Microsoft.XMLDOM‘);
                xmlDocument.async = false;
                //The responseText is loaded into XML document
                //Get Image
                var xmlElementImageId = 
                imageId = xmlElementImageId.text;
            var imgPhoto;
            imgPhoto = window.document.getElementById(
            imgPhoto.src = "ImagePage.aspx?s=l&id=" + imageId;

The images are retrieved from the database as an array of bytes, and are written to the Image.aspx web page, with in turn is used as an "src" attribute for the thumbnails image or the imgPhoto image control.

private void Page_Load(object sender, System.EventArgs e)
    string sSQL = "";
    SqlDataReader drData = null;
    SqlCommand cmd = null;
    SqlConnection cnn = new SqlConnection(SqlHelper.connectionString()); 
    string id = Request.Params["id"].ToString();
    string s = Request.Params["s"].ToString(); 

    if (s == "s")
        sSQL = "SELECT ImageSmall FROM Images WHERE ImageId=" + id.ToString();
        sSQL = "SELECT ImageLarge FROM Images WHERE ImageId=" + id.ToString();
        using (cmd = new SqlCommand())
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = sSQL;
            cmd.Connection = cnn;
            drData = cmd.ExecuteReader(); 
            if (drData.Read())
            if (s == "s")
//catch { }

The user can add new images to the photo album using the "Add New Image" button. To save the images into the database, they are first read into the array of bytes.

len1 = File1.PostedFile.ContentLength;
imageSmall = new byte[len1];
imageLarge = new byte[len1];
File1.PostedFile.InputStream.Read(imageLarge, 0, len1);

Just before being saved into the database, the posted image is resized to the required sizes.

imageSmall = ImageClass.ResizeImage(250, imageLarge);
imageLarge = ImageClass.ResizeImage(250, imageLarge);
public static byte[] ResizeImage(int newWidth, byte[] pictureBytes)
    Bitmap b = (Bitmap)Bitmap.FromStream(new MemoryStream(pictureBytes));
    int imageWidth = b.Width;
    int imageHeight = b.Height;  
    double newHeightD = Convert.ToDouble(newWidth) / 
           Convert.ToDouble(imageWidth) * Convert.ToDouble(imageHeight);
    int newHeight = Convert.ToInt32(newHeightD);
    Bitmap output = new Bitmap(b, new Size(newWidth, newHeight));
    MemoryStream ms = new MemoryStream();
    output.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
    byte[] bmpBytes = ms.GetBuffer();

    return bmpBytes;

The live sample can viewed at


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Ekaterina Kostrioukova
Web Developer
Canada Canada
Born in Russia, St.Petersburg. Graduated St.Petersburg State University as astrophysics.
Live in Canada, Toronto since 1997.
Worked as Software Developer, Solutions Architect, Database Designer and Administrator, Software Development Manager. During last 4 years was working as Sr. NET Consultant in various financial institutions and companies.
Have the following Microsoft certificates: MCP, MCSD, MCDBA.

You may also be interested in...

Comments and Discussions

GeneralHow Delete The Image? Pin
hamid_wairless1-Aug-12 6:17
memberhamid_wairless1-Aug-12 6:17 
Questionwhat is tirex Pin
alexanderanos1-Apr-12 3:21
memberalexanderanos1-Apr-12 3:21 
Generalchanges to be done to work in IIS 7 Pin
nasso7-Apr-11 6:38
membernasso7-Apr-11 6:38 
QuestionTirex? Pin
vmaranhao19-Mar-10 3:04
membervmaranhao19-Mar-10 3:04 
GeneralAJAX LIB / AddImage commented / linkbutton error Pin
boelenski4-Feb-10 0:41
memberboelenski4-Feb-10 0:41 
QuestionHow would you go about converting this sample to not use a database? Pin
Brian Harvey30-Aug-09 16:07
memberBrian Harvey30-Aug-09 16:07 
GeneralThe adding a new picture to the Database module Pin
rhender94-Aug-09 5:19
memberrhender94-Aug-09 5:19 
Generalerror Pin
williags19-Dec-08 10:13
memberwilliags19-Dec-08 10:13 
GeneralRe: error Pin
Ekaterina Kostrioukova24-Dec-08 4:25
memberEkaterina Kostrioukova24-Dec-08 4:25 
QuestionWhy store images in a database? Pin
michmela4416-Dec-08 14:51
membermichmela4416-Dec-08 14:51 
AnswerRe: Why store images in a database? Pin
michmela4416-Dec-08 14:56
membermichmela4416-Dec-08 14:56 
GeneralRe: Why store images in a database? Pin
Ekaterina Kostrioukova17-Dec-08 14:17
memberEkaterina Kostrioukova17-Dec-08 14:17 
GeneralOk, Why do you need all this code Pin
Gevorg16-Dec-08 13:57
memberGevorg16-Dec-08 13:57 
GeneralRe: Ok, Why do you need all this code Pin
Ekaterina Kostrioukova18-Dec-08 5:13
memberEkaterina Kostrioukova18-Dec-08 5:13 
GeneralRe: Ok, Why do you need all this code Pin
Gevorg18-Dec-08 5:46
memberGevorg18-Dec-08 5:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.181117.1 | Last Updated 16 Dec 2008
Article Copyright 2008 by Ekaterina Kostrioukova
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid