Click here to Skip to main content
15,867,834 members
Articles / Web Development / HTML

Show an image saved in a SQL Server table on an ASP.NET Image control

Rate me:
Please Sign up or sign in to vote.
4.75/5 (3 votes)
20 Oct 2011CPOL 54.1K   8   5
How to show an image saved in a SQL Server table on an ASP.NET Image control.

In a previous entry, I have shown how to store images to a database table. Now I will show you how to retrieve it and show it on an ASP.NET Image control. There is no straightforward method for showing it like “ImageControl.Image = ImageStream….” However it can be achieved using a Generic Handler.

Add a ‘Generic Handler’ to your ASP.NET web application. And in this example I will name it ‘getImageFromDB.ashx’. By default, IHttpHandler will be implemented (ProcessRequest and IsReusable methods will be implemented). And I will add another method called ‘GetImage’ and alter the ‘ProcessRequest’ method. And the finished handler should be similar to this:

C#
1: using System;
   2: using System.Drawing;
   3: using System.Drawing.Imaging;
   4: using System.IO;
   5: using System.Web;
   6: using System.Data;
   7: using System.Data.SqlClient;
   8:  
   9: namespace MyWebApplication
  10: {
  11:    
  12:     public class getImageFromDB : IHttpHandler
  13:     {
  14:         public void ProcessRequest(HttpContext context)
  15:         {
  16:             context.Response.Clear();
  17:  
  18:             if (!String.IsNullOrEmpty(context.Request.QueryString["empID"]))
  19:             {
  20:                 int id = Int32.Parse(context.Request.QueryString["empID"]);
  21:  
  22:                 Image image = GetImage(id);
  23:  
  24:                 context.Response.ContentType = "image/jpeg";
  25:                 image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
  26:             }
  27:             else
  28:             {
  29:                 context.Response.ContentType = "text/html";
  30:                 context.Response.Write("<p>Need a valid id</p>");
  31:             }
  32:         }
  33:  
  34:         public bool IsReusable
  35:         {
  36:             get
  37:             {
  38:                 return false;
  39:             }
  40:         }
  41:  
  42:         private Image GetImage(int empID)
  43:         {
  44:  
  45:             MemoryStream memoryStream = new MemoryStream();
  46:             //Retrieve image from Database to a memeory stream.
                  // If you are using a different method, use it and assign
                  // the data to the 'memoryStream' variable.
  47:  
  48:             string connectionString = "Password=PWD;Persist Security " + 
                    "Info=True;User ID=USER;Initial Catalog=SampleDatabase;Data Source=SQLSERVER";
  49:             using (SqlConnection sqlConnection = new SqlConnection(connectionString))
  50:             {
  51:                 using (SqlCommand sqlCommand = new SqlCommand("SELECT emp_id, " + 
                       "emp_name, emp_image FROM Employee where emp_id = " + 
                       empID.ToString(), sqlConnection))
  52:                 {
  53:                     sqlConnection.Open();
  54:                     SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
  55:  
  56:                     if (sqlDataReader.HasRows)
  57:                     {
  58:                         sqlDataReader.Read();
  59:                         byte[] btImage = (byte[])sqlDataReader["emp_image"];
  60:  
  61:                         memoryStream = new MemoryStream(btImage, false);
  62:                     }
  63:                 }
  64:                 sqlConnection.Close();
  65:             }
  66:             return Image.FromStream(memoryStream);
  67:         }
  68:     }
  69: }

And you can call the handler and display the image using the following syntax:

C#
1: private void GetImageFromDatabase(int empID)
2: {
3:     imageControl.ImageUrl = "getImageFromDB.ashx?empID=" + empID.ToString();
4: }

License

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


Written By
Technical Lead Air Liquide Industrial Services (Singapore)
Singapore Singapore
My passion lies in building business intelligence and data-based solutions, writing about things I work with and talking about it. New technologies relevant to my line of work interest me and I am often seen playing with early releases of such technologies.

My current role involves architecting and building a variety of data solutions, providing database maintenance and administration support, building the organization’s data practice, and training and mentoring peers.

My aspiration over the next several years is to achieve higher competency and recognition in the field of Data Analytics and move into a career of data science.


Specialities: SQL Server, T-SQL Development, SQL Server Administration, SSRS, SSIS, C#, ASP.Net, Crystal Reports

Comments and Discussions

 
Questioni try this code but i have error Pin
Member 1071242831-Mar-14 1:22
Member 1071242831-Mar-14 1:22 
QuestionShow an image saved in a SQL Server table on an ASP.NET Image control - query Pin
hygrsrir198719-Apr-12 0:39
hygrsrir198719-Apr-12 0:39 
Dear Friend,

I tried to use the above coding to get image from db into image control,

In this : return Image.FromStream(memoryStream);

I got an error as : 'Parameter is not valid'

Please help!
QuestionShow an image saved in a SQL Server table on an ASP.NET Image control Pin
hygrsrir198719-Apr-12 0:38
hygrsrir198719-Apr-12 0:38 
AnswerRe: Show an image saved in a SQL Server table on an ASP.NET Image control Pin
Manjuke Fernando19-Apr-12 3:38
professionalManjuke Fernando19-Apr-12 3:38 
GeneralRe: Show an image saved in a SQL Server table on an ASP.NET Image control Pin
ABM Abdul Muttalib26-Jan-15 2:17
ABM Abdul Muttalib26-Jan-15 2:17 

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.