Click here to Skip to main content
15,881,559 members
Articles / Web Development / ASP.NET

SQL Database Image Storage & Easy Thumbnails

Rate me:
Please Sign up or sign in to vote.
4.82/5 (62 votes)
17 May 20077 min read 464.2K   8.9K   278  
Shows how to store images in SQL Database Image Storage & create Thumnails easiliy from
using System;
using System.Data;
using System.Configuration;
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 System.IO;

public partial class _Default : System.Web.UI.Page
{

    #region instance fields
    //instance fields
    protected System.Web.UI.WebControls.Image imgImage;
    private int THUMBNAIL_SIZE = 60;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// Creates an image, by querying the SQL database with the given img_pk
    /// parameter. The query will return a byte[] array, which represents the image.
    /// This byte[] array is then converted into an image and added to the placeholder
    /// control "plImage" which is on this page
    /// </summary>
    /// <param name="img_pk">The primary key to fetch the image data for</param>
    private void createImageFromDBBytes(int img_pk)
    {

        ThumbFromID.THUMBNAIL_SIZE = this.THUMBNAIL_SIZE;
        ThumbFromID.USE_SIZE_FOR_HEIGHT = false;
        imgImage = new System.Web.UI.WebControls.Image();
        // set the source to the page that generates the thumbnail image
        imgImage.ImageUrl = ThumbFromID.PAGE_NAME + "?" +
            ThumbFromID.IMAGE_ID + "=" + img_pk;
        litException.Visible = false;
        plImage.Controls.Clear();
        plImage.Controls.Add(imgImage);
    }

	/// <summary>
	/// returns a byte[] array which represents the input Image
	/// </summary>
	/// <param name="bmp">The source image to return as byte[] array</param>
	/// <returns>byte[] array which represents the input Image</returns>
    private byte[] BmpToBytes(System.Drawing.Image bmp)
    {
        MemoryStream ms = null;
        byte[] bmpBytes = null;
        try
        {
            ms = new MemoryStream();
            // Save to memory using the Jpeg format
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            // read to end
            bmpBytes = ms.GetBuffer();
        }
        catch (Exception ex)
        {
            return null;
        }
        finally
        {
            bmp.Dispose();
            if (ms != null)
            {
                ms.Close();
            }
        }
        return bmpBytes;
    }

    /// <summary>
    /// Will attempt ot save the posted file contents to SQL server
    /// table. Will firstly check that the posted file is an image
    /// </summary>
    /// <param name="sender">the btnSubmit</param>
    /// <param name="e">the btnSubmit EventArgs</param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            string imgContentType = UploadFile.PostedFile.ContentType;

            //check if an image
            if (imgContentType.ToLower().StartsWith("image"))
            {
                //get the image from upload stream
                System.Drawing.Bitmap b = (System.Drawing.Bitmap)System.Drawing.Image.FromStream(UploadFile.PostedFile.InputStream);
                //get pk, to allow image to be created on this page from the
                //SQL server stores byte[] array
                int img_pk = 0;
                //store the image in database, and also ccheck to see if it was successful, and if so create 
                //a thumnail here of the stored image
                int RowsAffected = dbAccess.SaveImageToDB(ref img_pk,BmpToBytes(b));
                if (RowsAffected > 0)
                {
                    createImageFromDBBytes(img_pk);
                }
                else
                {
                    litException.Text = ("<br><p>ERROR saving image </p>");
                }
            }
            else
            {
                litException.Text = ("<br><p>The file is not an image</p>");
            }
        }
        catch (Exception ex)
        {
            litException.Text = ("<br><p>" + ex.Message + "</p>");
        }
    }


    /// <summary>
    /// Will attempt fetch all SQL server stored images, and will bind the resultant
    /// DataSet to the "dlImages" datalist on this page. When the databinding occurs
    /// the dlImages_ItemDataBound(..) event is fired. At that stage the image control
    /// is found, and a new thumbnail is constructed for each DataSet row value
    /// </summary>
    /// <param name="sender">the btnSeeAll</param>
    /// <param name="e">the btnSeeAll EventArgs</param>
    protected void btnSeeAll_Click(object sender, EventArgs e)
    {
        try
        {
            // set the source of the data for the repeater control and bind it
            DataSet dsImgs = dbAccess.GetImages();
            dlImages.DataSource = dsImgs;
            dlImages.DataBind();
        }
        catch (Exception ex)
        {
            litException.Text = ("<br><p>" + ex.Message + "</p>");
        }
    }


    /// <summary>
    /// Occurs when the server side DataList starts databinding. This event
    /// is used to intercept the databinding to create a new Image that
    /// uses the binary array value of the data within the DataList datasource
    /// </summary>
    /// <param name="sender">the datalist</param>
    /// <param name="e">the datalist DataListItemEventArgs</param>
    protected void dlImages_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        System.Web.UI.WebControls.Image img = null;

        // make sure this is an item in the data list (not header etc.)
        if ((e.Item.ItemType == ListItemType.Item) ||
            (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            // get a reference to the image used for the bar in the row
            img = (System.Web.UI.WebControls.Image)
                (e.Item.FindControl("imgThumbnail"));

            //get the img_pk from DataRow being bound
            int img_pk = Convert.ToInt16(
                ((DataRowView)e.Item.DataItem).Row.ItemArray[0].ToString());

            ThumbFromID.THUMBNAIL_SIZE = this.THUMBNAIL_SIZE;
            ThumbFromID.USE_SIZE_FOR_HEIGHT = false;
            // set the source to the page that generates the thumbnail image
            img.ImageUrl = ThumbFromID.PAGE_NAME + "?" +
                ThumbFromID.IMAGE_ID + "=" + img_pk;            
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2016
  • Codeproject MVP 2016
  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Comments and Discussions