Sunday, October 16, 2011

Displaying Images as a thumbnail image in a DataView from Database in ASP.NET

In this article i will be showing a example to retrieve image from Database and to display it as a thumbnail image in a dataview.

I have stored the image in a table named tblImage. SQL Server supports a datatype named as image for storing the image. 

A brief description about image datatype is as follows:-

image : Variable-length binary data from 0 through 2^31-1 (2,147,483,647) bytes.

The following query can be used to create a table:

CREATE TABLE [dbo].[tblImage] (
        [ID] [int] IDENTITY ,
        [Image_Name] [varchar] (500) NULL ,
        [Image] [image] NULL
)
In the create table statement, ID is declared as IDENTITY column.

Now I will be creating a simple Image Handler page using aspx page, that will be used to retrieve images from the database and write them to the Response Stream. The image ID will be passed as a QueryString to this image handler page, based on which the image byte array will be retrieved from database table and will be written to Response stream.

Step 1: ImageThumbnailCreation.aspx.cs

This class will work as a handler for processing the retrieved byte array from database and to write it as a Response stream.

public partial class ImageThumbnailCreation : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
    if (Request.QueryString["ID"] != null//tblImage ID column value
    {
     string strQuery = "select Image from tblImage where ID=@ID";
     string strID = Request.QueryString["ID"];

     //defining the connection string for the SqlConnection object
     SqlConnection connection = new  
     SqlConnection(@"server=MyPC;database=master;uid=sa;pwd=password1");

     //opening the connection
     connection.Open();
     
     SqlCommand cmd = new SqlCommand(strQuery);

     //creating a parameter and binding it to the command object
     cmd.Parameters.Add("@id", SqlDbType.Int).Value= Convert.ToInt32(strID);                               
     cmd.CommandType = CommandType.Text;
     cmd.Connection = connection;

     //retrieving the byte array from command object
     byte[] byteArray = (byte[])cmd.ExecuteScalar();               
              
     //Creating image from the retrieved byteArray
     System.Drawing.Image image = System.Drawing.Image.FromStream(new 
     MemoryStream(byteArray));
     
     //Creating the thumnailimage
     System.Drawing.Image thumbImage = image.GetThumbnailImage(80,80, new 
     System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

     // memory stream object to store image bytes
     MemoryStream imgStream = new MemoryStream();

     // storing image into the memory stream
     thumbImage.Save(imgStream, System.Drawing.Imaging.ImageFormat.Jpeg);

     // byte array declaration as the same size of the image
     byte[] byteImage = new Byte[imgStream.Length];

     // resetting the memory stream
     imgStream.Position = 0;

     // load the byte array with the image
     imgStream.Read(byteImage, 0, (int)imgStream.Length);

     // return byteImage to caller with image type
     Response.ContentType = "image/jpeg";
     Response.BinaryWrite(byteImage);
    }
 }

 public bool ThumbnailCallback()
 {
   return true;
 }
}

Step 2: Using Template Field with Image Control on GridView (ShowingImageinGridView.aspx)

The GridView, contains the following columns:
a) ID column as BoundField
b) Image Name column as BoundField
c) Image column as a TemplateField with a Image control

It can be seen that the Image control ImageUrl property is referring to the respective handler page (ImageThumbnailCreation.aspx) and ID using the Eval statement.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" RowStyle-Width="100%">
 <Columns>
   <asp:BoundField HeaderText="ID" DataField="ID" />
   <asp:BoundField HeaderText="Image Name" DataField="Image_Name" />               
   <asp:TemplateField HeaderText="Image">
   <ItemTemplate>
    <asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageThumbnailCreation.aspx?ID=" + 
     Eval("ID")%>'/>
   </ItemTemplate>
   </asp:TemplateField>
 </Columns>
</asp:GridView>

In the code behind of ShowingImageinGridView.aspx, following code is used to retrieve the image byte array from database and binding it to the GridView control.

void RetrieveAndBindImage()
{
 //defining the connection string for the SqlConnection object
 SqlConnection connection = new 
 SqlConnection(@"server=MyPC;database=master;uid=sa;pwd=password1");

 try
 {
    //opening the connection
    connection.Open();

    SqlCommand cmd = new SqlCommand();
    
    //select statement creation as a commandText
    cmd.CommandText = "Select * from tblImage";
    cmd.Connection = connection;
    
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    GridView1.DataSource = ds;
    
    GridView1.DataBind();
 }
 catch (Exception ex)
 {  }

 finally
 {
   if (connection != null)
       connection.Close();
 }
}

Following figure below displays the GridView with the thumbnail images from database:

Using this article one can create and show thumbnail images on the GridView control in aspx page.

Happy Coding....

No comments :

Post a Comment