Home   |  Articles   |  Resources   |  Humor   |  Feedback       

  Login   Register 

Ads Via DevMavens


Retrieve Images from a SQL database for display in an Asp.Net Datagrid

Posted by on Saturday, July 10, 2004

This article demonstrates how to read images data type (BLOB data) from a SQL database and display it in an ASP.Net page

In our last article, Saving Images in a SQL database, we covered how to upload client images into a SQL database. In this article we will demonstrate how to retrieve the images (BLOB data) from a SQL database and display them in a ASP.Net datagrid. Our first step is to read the data from the Images table we have already created.

SELECT ImageKey, ImageName, Images, ImageType FROM Images

Now, let’s take a look at our datagrid:

<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False">
   <Columns>
     <asp:BoundColumn DataField="ImageIdentity" HeaderText="ImageIdentity"

Visible=False></asp:BoundColumn>
     <asp:BoundColumn DataField="ImageName" HeaderText="Image

Name"></asp:BoundColumn>
     <asp:BoundColumn DataField="ImageType" HeaderText="Image

Type"></asp:BoundColumn>
     <asp:TemplateColumn  HeaderText="Image">
         <ItemTemplate >
            <img runat="server"
                 src='<%# "getImage.aspx?ID=" + DataBinder.Eval(Container.DataItem,
                 "ImageIdentity")  %>' ID="Img1"/>
         </ItemTemplate>
     </asp:TemplateColumn>
   </Columns>

</asp:DataGrid>

The first three columns: ImageIdentity, ImageName, and ImageType, are perfectly simple – these are bound columns, and all we need to do is set the DataField property to the column name in the datasource for the grid. The last column (Img1) is more interesting since you cannot bind a column to an image data type. Images are traditionally displayed in web pages using the HTML<IMG> tag, and that is what we are doing within our templated column as well. However, instead of having a static path to an image on the web server, the source of the image is a web page. 

The first thing we need to do in getImage.aspx is retrieve the image and ContentType of the image we want to display. By passing the key field for this record in the QueryString we can use the code below.

      System.Data.SqlClient.SqlDataReader Reader=null;
      string ImageIdentity = Request.QueryString["ID"].ToString();
      SqlConnection sqlConnection = new SqlConnection(@"initial catalog=Articles;user

id=sa;password=;server=myServer");
      sqlConnection.Open();    
      SqlCommand sqlCommand = new SqlCommand("Select Images,ImageType from Images where

imageKey="+ImageIdentity  ,sqlConnection);
      Reader= sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
      Reader.Read();

Our next step is to read the image into a byte array

      byte [] byteArray = (byte[]) Reader["Images"];


All that is left for us to do is specify the ContentType for the page, and use a BinaryWrite to move data from our byte array to the output of the page.

      Response.ContentType=Reader["ImageType"].ToString();
      Response.BinaryWrite(byteArray);

Since this is a datagrid column however, maybe we want to display a thumbnail of the image. To draw a thumbnail we are going to create a System.Drawing.Image object which allows us to resize the image into something more appropriate for display in our datagrid.


System.IO.MemoryStream mstream =
new System.IO.MemoryStream(byteArray,0,byteArray.Length);
System.Drawing.Image dbImage =
System.Drawing.Image.FromStream( new System.IO.MemoryStream(byteArray));
System.Drawing.Image thumbnailImage =
dbImage.GetThumbnailImage(100,100,null,new System.IntPtr());
thumbnailImage.Save(mstream,dbImage.RawFormat);
Byte[] thumbnailByteArray = new Byte[mstream.Length];
mstream.Position = 0;
mstream.Read(thumbnailByteArray, 0, Convert.ToInt32(mstream.Length));
Response.Clear();
Response.ContentType=Reader["ImageType"].ToString();
Response.BinaryWrite(thumbnailByteArray);

Now we want to get a little more ambitious with our page. We want to be able to click on the datagrid image column which contains the thumbnail of our database image, and view the full size image.

<ItemTemplate >
  <a href='<%# "getImage.aspx?ThumbNail=\"N\"&ID=" + DataBinder.Eval(Container.DataItem,
                   "ImageIdentity")  %>'>
      <img runat="server" src='<%# "getImage.aspx?ID=" + DataBinder.Eval
(Container.DataItem, "ImageIdentity")%>' ID="Img1"/>
  </a>
</ItemTemplate>

Since we already have the getImage.aspx page coded, all we do is pass an additional parameter in the query string, so that the page knows whether to display the full size image or the thumbnail.

 

Login to Download code



 

by Poonam Lall


Comments:

Job Well Done!!!
By karra on 7/15/2004
Poonam,

Nice Work!! I was struggling to find a solution to this problem from last 2 days. I feel you solution has helped me to prevent breaking my head.

Nice posting right on time. Keep it up.

Karra

Image display in datagrid not working
By sriram_govi on 7/15/2004
Hi,

I tried to implement the same code for uploading and displaying images.

but when i try to retrive image and display in datagrid, i get the following error:


Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compilation error

Compiler Error Message: BC32017: Comma, ')', or a valid expression continuation expected.

Source Error:
Line 18: <asp:TemplateColumn HeaderText="Image">
Line 19: <ItemTemplate>
Line 20: <a href='<%# "getImage.aspx?ThumbNail=\"N\"&ID=" + DataBinder.Eval(Container.DataItem,
Line 21: "ImageIdentity") %>'>
Line 22: <img runat="server" src='<%# "getImage.aspx?ID=" + DataBinder.Eval(Container.DataItem,


----------------------

Line 20 is marked red. i tried a lot to get thru, but couldnt. Can someone please help me. I am new to asp.net.

any help in this regard would be highly appreciated.

thanks in advance,

Sriram

error
By amolabravo on 7/25/2004
I get an IE error "Memory could not be read"

Displaying SQL Images in an ASP.Net Datagrid
By cpearson on 8/4/2004
I had been working on a similiar example but got an exception when creating the Image object from a stream.

In getImage.aspx.cs file you have the same type of code I was using:

System.Drawing.Image dbImage = System.Drawing.Image.FromStream(new System.IO.MemoryStream(byteArray));

As with my code, your code also threw an exception, "Invalid parameter used."

I wired the database to use Northwind.Employees the Image being the Photo column. What Sql Server data type did you use to make the sample work? Northwind.Employees.Photo is of type image.

Copyright 2004 OdeToCode.com 


The Blogs
Subscribe to the OdeToCode blogs for the latest news, downloads, new articles, and quirky commentary.
New Articles
Databinding in Silverlight
This article will cover data binding features in Silverlight, including binding expressions, validation, converters, and binding modes.

The Standard LINQ Operators
This article will cover the standard LINQ operators provided by LINQ for filtering, grouping, joining, converting, projecting, and more.

C# 3.0 and LINQ
C# 3.0 introduced a number of new features for LINQ. In this article we'll examine the new features like extension methods, lambda expressions, anonymous types, and more.

Most Popular Articles
Table Variables In T-SQL
Table variables allow you to store a resultset in SQL Server without the overhead of declaring and cleaning up a temporary table. In this article, we will highlight the features and advantages of the table variable data type.

ASP.Net 2.0 - Master Pages: Tips, Tricks, and Traps
MasterPages are a great addition to the ASP.NET 2.0 feature set, but are not without their quirks. This article will highlight the common problems developers face with master pages, and provide tips and tricks to use master pages to their fullest potential.

AppSettings In web.config
In this article we will review a couple of pratices to keep your runtime configuration information flexible.

Contribute Code
Privacy
Consultancy