Skip to main content

Display Images from SQL Server in ASP.NET Page with Generic Handler

In order to display an image stored in SQL Server on the Web Form, we need the concept of Generic Handler in ASP.NET. A Generic Handler is just any other web form that is added in the current form. A generic handler is responsible for fulfilling requests from a browser. A handler is a class that implements IHttpHandler interface. Normally the generic handler is having an extension of “Handler.ashx”.

In my previous post, I discussed about the storing of an image in SQL Server which the user selects on the web page (.aspx) page. I will be continuing from the same process. The following interface is used:


In the above screen shot, a textbox is there in which the Image id will be entered by the user which the user wants to display. Also the button will be used to show the same. And lastly an image control that will display the image fetched from the database.


On the Show Image button the following coding is to be done. The hander is invoked with the help of following code:

Protected void ShowImage_Click(object sender, EventArgs e)
{
       Image1.ImageUrl = “Hander.ashx?id=”+TextBox1.Text;
}
Next Step is to add a generic handler from WebSite Menu and select Add new Item:



using System;
using System.Web;
using System.Data.SqlClient;

public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
       context.Response.ContentType = "text/plain";
       context.Response.Write("Hello World");
       String vImageID = context.Request.QueryString["id"];
       SqlConnection vConn = new SqlConnection();
       vConn.Open();
       String vQuery = "Select * From ImageTable where id = @id";
       SqlCommand vComm=new SqlCommand (vQuery,vConn);
       vComm.Parameters.AddWithValue("@id",vImageID);
       SqlDataReader myReader= vComm.ExecuteReader();
      while(myReader.Read())
      {
          context.Response.ContentType="image/jpg";
          context.Response.BinaryWrite((byte[])myReader["Photo"]);
      }
      myReader.Close();
     vConn.Close();
   }
   public bool IsReusable {
  get {
        return false;
     }
 }
}

In the above coding, we are trying to get the ID of the image which the user has entered in the previous page. And then we are doing the following stuff:

1. Open the database connection.

2. Fire query which gets the image of the selected user id which the user has passed from the previous page.

3. Reading the image in the form of DataReader.

4. And ultimately writing the DataReader with the help of context.Response.BinaryWrite. When we use this we need to typecast in the format of byte[] array because the image is also stored in the format of bytes.

I hope this article will help you in displaying images on web form (.aspx) page that are fetched out from a database.

Have nice time....

Comments

Gautam said…
THIS IS ONE LINE CODE TO, HOW TO RETRIVE (IMAGE)DATA FROM SQL

byte[] blob = (byte[])rd["PicImage"];
MemoryStream ms = new MemoryStream(blob);
ms.Write(blob, 0, (int)blob.Length);
Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(ms.ToArray());

Popular posts from this blog

How to use QueryExtenderControl in ASP.NET with LINQ

Queryextender control is a control that helps in doing actions like filtration, searching, sorting etc. on the LINQ Data source with few steps. In fact we don’t have to write any code with this. Screenshot given below is just an example that can easily be achieved through this control. In the above screenshot, we can see that there is a GridView Control that has been binded to a LINQData Source Control. And we have a DropDownlistBox that is also binded to another LINQData Source Control and displaying only grouped jobs. The GridView display all the employees who are matching the Job Parameter. This is done through QueryExtender Control. Also we can search for any name in the employee name's through Query Extender control. The code in the HTML goes like: < form id ="form1" runat ="server">     < div >         Select Job: < asp : DropDownList ID ="Job" runat ="server" DataSourceID ="LinqDataSource2...

Using GUID or UniqueIdentifiers in SQL Server

In order to differentiate between two rows, we normally use primary keys or identity values which may be same across two tables. In order to overcome this problem we can use a special type named "GUID" . Its a hexadecimal number (Base 16) and the advantage is  that they are unique across all databases and tables.  In SQL Server the same concept is implemented through UNIQUEIDENTIFIER  data type. In order to generate a new value, we use the NEWID() function. For e.g.  a. Creating a table that uses the UNIQUEIDENTIFIER datatype Create table Test ( Empno uniqueidentifier, Ename varchar(20) ) b. Inserting rows in the tables with the use of NEWID() function insert into Test values (newId(),'ABC') insert into Test values (newid(),'XYZ') insert into test values (newid(),'MNO') c. Selecting the rows from the table. Select * from test  Empno                             ...

How to Delete Record through Knex.

This post is all about of deleting records through KNEX ORM in Nodejs. The following code shows how to achieve this: knex("depts").where("deptno","50").del() .then(function (count) {     console.log(count); }) .finally(function () {     knex.destroy(); }); The above code deletes a record from a table "Depts" where Deptno = 50. It has a "then" Promise attached that will show how many records were deleted with this command. Also "finally" is the method that will always execute and will close the KNEX connection. Happy Coding !!!