ASP.Net Image Handler to retrieve Image from Database

While Creating and Saving Image in Database I was facing an issue of retrieving image from Database and then assign that  image into Gridview’s image control. To resolve this issue, I have implemented Image handler code.

I used below code to save image in database and then display it in Gridview using Http handler

Save Button Code (Save Image in Database)

 protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            
            Byte[] bytes = null;

            // Read the file and convert it to Byte Array
            string filePath = FileUpload1.PostedFile.FileName;
            string filename = Path.GetFileName(filePath);
            string ext = Path.GetExtension(filename);
            string contenttype = String.Empty;

            //Set the contenttype based on File Extension
            switch (ext)
            {                
                case ".jpg":
                    contenttype = "image/jpg";
                    break;
                case ".jpeg":
                    contenttype = "image/jpeg";
                    break;
                case ".png":
                    contenttype = "image/png";
                    break;
                case ".gif":
                    contenttype = "image/gif";
                    break;               
            }
            if (contenttype != String.Empty)
            {
                Stream fs = FileUpload1.PostedFile.InputStream;
                BinaryReader br = new BinaryReader(fs);
                bytes = br.ReadBytes((Int32)fs.Length);
            }
            else
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "File format not recognised.Please Upload Valid File.";
            }

            //Database Connection 
            SqlConnection sqlserverconnection = new SqlConnection(strDBConnection);

            //SQL Database Connection Open
            sqlserverconnection.Open();

            string strQuery;

            strQuery = "sp_InsertEmployee";
			 
            SqlCommand command = new SqlCommand(strQuery, sqlserverconnection);

            command.CommandType = System.Data.CommandType.StoredProcedure;

            command.Parameters.AddWithValue("@EmployeeType", ddlEmployeeType.SelectedItem.Text.ToString());
            command.Parameters.AddWithValue("@FullName", txtFullName.Text.ToString());
            command.Parameters.AddWithValue("@Designation", txtDesignation.Text.ToString());
            command.Parameters.AddWithValue("@Department", ddlDepatment.SelectedItem.Value.ToString());
            command.Parameters.AddWithValue("@ContactNo", txtContactNo.Text.ToString());
            command.Parameters.AddWithValue("@Email", txtEmail.Text.ToString());
            string dob = String.Format("{0}", Request.Form["txtDOB"]);
            command.Parameters.AddWithValue("@DOB", dob);
            command.Parameters.AddWithValue("@Education", txtEducation.Text.ToString());
            command.Parameters.AddWithValue("@Address", txtAddress.Text.ToString());
            command.Parameters.AddWithValue("@ExpInYears", txtEXP.Text.ToString());
            command.Parameters.AddWithValue("@Username", txtUserName.Text.ToString());
            command.Parameters.AddWithValue("@Password", txtPassword.Text.ToString());
		    command.Parameters.AddWithValue("@Photo", bytes);

            command.ExecuteNonQuery();

            //SQL Connection Close
            sqlserverconnection.Close();

            lblMessage.Text = "Employee Information Added Successfully";
            lblMessage.ForeColor = System.Drawing.Color.Green;
            lblMessage.Font.Bold = true;

            ClearControl();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

ViewEmployee Page is going to get all employee Detail and bind all information into Gridview.
Gridview contain Image tag which displays Employee Image.
GridView Image control Code:

<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?id="+ Eval("EmployeeID") %>' Height="80px" Width="80px" />

Here ImageHandler.ashx is custom HTTP handler which is responsible to return employee Image as per EmployeeID
To add HTTP Handler right click project > Add New Item > Generic Handler > ImageHandler.ashx.
Code For ImageHandler.ashx

&lt;%@ WebHandler Language="C#" Class="ImageHandler" %&gt;

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public class ImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext ctx)
    {
        string id = ctx.Request.QueryString["id"];

        String strDBConnection = ConfigurationManager.AppSettings["DatabaseConnection"];

        SqlConnection sqlserverconnection = new SqlConnection(strDBConnection);
        SqlConnection con = new SqlConnection(strDBConnection);
        SqlCommand cmd = new SqlCommand("Select Photo From EmployeeMaster Where EmployeeID = @EmpID", con);
        cmd.CommandType = CommandType.Text;

        cmd.Parameters.AddWithValue("@EmpID", id);

        con.Open();
        byte[] pict = (byte[])cmd.ExecuteScalar();
        con.Close();

        ctx.Response.BinaryWrite(pict);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s