ImageHandler.ashx Csharp Code To Convert Images to Bytes and Bind to Datalist and Gridview in Asp.net


ImageHandler.ashx Csharp Code To Convert Images to Bytes and Bind to Datalist and Gridview in Asp.net

  1. Open ImageHandler.ashx File which you have created inside the Controls Folder.You can add the following piece of csharp code in the ImageHandler.ashx file
  2. In this social networking project we are storing all the Profile pictures inside the database and not in any folder.
  3. Firstly we are converting the uploaded image into bytes using csharp and then storing it in database table column of datatype as image.
  4. Storing the image in databse is quite simple using csharp but for retriving the images from database we need an HTTPHandler and so we have created ImageHandler.
  5. We are sending the RegisterId of the user to fetch the profile picture.Based on the RegisterId we are fetching the profile picture and converting it back into bytes and then binding it to respective controls like gridview or datalist

ImageHandler.ashx C# Code:

 <%@ WebHandler Language="C#" Class="ImageHandler" %>

using System;
using System.Web;
using System.IO;
using System.Data;

public class ImageHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {


        if (context.Request.QueryString["RegisterId"] != null)
        {
            string RegisterId = context.Request.QueryString["RegisterId"];
            DataTable dt = new DataTable();
            string query = "select ProfilePic from Register where RegisterId='" + RegisterId + "'";
            dt = Database.GetData(query);

            context.Response.BinaryWrite((Byte[])dt.Rows[0]["ProfilePic"]);
            context.Response.End();
        }
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}


0 comments:

Post a Comment