Use Generic Handler to Display Image in Asp.net

Generic Handlers in ASP.NET: Image Storage and Retrieval

Introduction:

Unlock the potential of image storage and retrieval in ASP.NET as we explore the implementation of a generic handler for seamless image handling. This comprehensive guide covers database creation, stored procedures, HTML markup, and C# coding to empower your web applications with dynamic image functionalities.

Use Generic Handler to Display Image in Asp.net

Creating Database and Stored Procedures:

Before diving into image handling, establish the groundwork by creating a database table for image storage and relevant stored procedures. The following SQL scripts outline the structure of the Image table and procedures for inserting and retrieving images:


-- Creating Database Table
create table Image(
    imgid int identity,
    imgtitle varchar(30),
    img varbinary(max)
)

-- Stored Procedure for Inserting Image Data
Create procedure [dbo].[spInsertImage](
    @imgTitle varchar(50),
    @image varbinary(MAX))
as
 begin
  insert into Image(imgtitle,img) values (@imgTitle,@image)
 end

-- Stored Procedure for Get Image by ImageTitle
Create procedure [dbo].[spGetImage](
    @imgTitle varchar(50))
as
 begin
  select * from Image where imgtitle=@imgTitle
 end


HTML Markup: Design Page for Image Upload:

Design a user-friendly page using HTML markup for image upload. The design includes a title input, a file uploader, and an upload button. Additionally, an ASP.NET Image control is set to display the uploaded image.


<div>
 <table>
  <tr> <th colspan="2">Upload Image</th> </tr>
  <tr>
   <td>Title : </td>
    <td>
      <asp:TextBox ID="txttitle" runat="server"></asp:TextBox>
    </td>
  </tr>
  <tr>
    <td>Upload Image :</td>
    <td>
      <asp:FileUpload ID="FileUploader1" runat="server" />
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    </td>
  </tr>
 </table>
</div>
<br />
<asp:Image ID="Image1" runat="server" Width="300px" Height="300px" />

C# Coding: Image Upload and Generic Handler:


  // C# Coding
  protected void btnUpload_Click(object sender, EventArgs e)
  {
   byte[] img = null;
   if (FileUploader1.HasFile)
   {
    img = Image.ConvertImagetoByte(FileUploader1.PostedFile);
    SqlCommand cmd = new SqlCommand("spInsertImage", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@imgTitle", txttitle.Text);
    cmd.Parameters.AddWithValue("@image", img);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
    Image1.ImageUrl = "~/ImageHandler.ashx?ImageID="+txtTitle.Text.Trim();           
   }        
  }
  
 // C# Coding for Generic Handler (ImageHandler.ashx) 
 public void ProcessRequest(HttpContext context)
 {
   string title = context.Request.QueryString["title"];
   if (title != "")
   {                
     SqlConnection connection = new SqlConnection("Server=.; Database=master; User Id=sa; Password=tiger;");
     SqlCommand cmd = new SqlCommand("[spGetImage]", connection);
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.Parameters.AddWithValue("@imgTitle", title);
     connection.Open();
     SqlDataAdapter da = new SqlDataAdapter(cmd);
     DataSet ds = new DataSet();
     da.Fill(ds);
     //Get Image Data
     byte[] file = null;
     if (ds.Tables[0].Rows.Count > 0)
     {
       file = (byte[])ds.Tables[0].Rows[0]["img"];
     }

      MemoryStream memoryStream = new MemoryStream();
      memoryStream.Write(file, 0, file.Length);
      context.Response.ContentType = "image/png";
      context.Response.Buffer = true;
      context.Response.BinaryWrite(file);
      memoryStream.Dispose();
   }
 }

Conclusion:

With this comprehensive guide, you've learned how to store and retrieve images in ASP.NET using a generic handler. From creating a database and stored procedures to designing the HTML markup and implementing C# coding, your web applications are now equipped with dynamic image handling capabilities. Elevate your development skills and enhance user experiences with this powerful image storage solution.

Post a Comment

0 Comments