Convert Binary data to image, Save and retrieve image from binary data asp.net c#

Convert binary Data to Image: This article will demonstrate how to display an image, save and retrieve an image from binary data typed saved in Ms-SQL database  i.e convert binary data into image in Asp.net C#. Mostly in many application where we use BioMetric hardware or webcam to capture images, we save those images into the database in binary format. Now when we need to display image from binary data from our database (MSSQL server) we have to add the generic handler.


Code to save and retrieve image ( binary data saved ) as below:

Add a .ashx page that you’ll target as an image URL. Then you need to write the byte array as response stream in the ProcessRequest method inside that handler as shown in below code snippet.

ShowImage.ashx

%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
public class ShowImage : IHttpHandler
{
  public void ProcessRequest(HttpContext context)
   {
      Int32 empno;
        if (context.Request.QueryString["id"] != null)
           empno = Convert.ToInt32(context.Request.QueryString["id"]);
        else
           throw new ArgumentException("No parameter specified");
       context.Response.ContentType = "image/jpeg";
       Stream strm = ShowEmpImage(empno);
       byte[] buffer = new byte[4096];
       int byteSeq = strm.Read(buffer, 0, 4096);
       while (byteSeq > 0)
       {
         context.Response.OutputStream.Write(buffer, 0, byteSeq);
         byteSeq = strm.Read(buffer, 0, 4096);
       }      
    }
 
   public Stream ShowEmpImage(int empno)
   {  string conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
       SqlConnection connection = new SqlConnection(conn);
       string sql = "SELECT imageCOl FROM  table WHERE empid = @ID";
       SqlCommand cmd = new SqlCommand(sql,connection);
       cmd.CommandType = CommandType.Text;
       cmd.Parameters.AddWithValue("@ID", empno);
       connection.Open();
       object img = cmd.ExecuteScalar();
       try
       {
         return new MemoryStream((byte[])img);
       }
        
 catch 
  { return null; }
        
 finally 
  { connection.Close(); }
     }
   public bool IsReusable
   {
        get { return false;  }
   }
}

Default page.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class _Default : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
 SqlConnection connection = null;
try
 {
 FileUpload img = (FileUpload)imgUpload;
 Byte[] imgByte = null;
 if (img.HasFile && img.PostedFile != null)
 {
 //To create a PostedFile
 HttpPostedFile File = imgUpload.PostedFile;
 //Create byte Array with file len
 imgByte = new Byte[File.ContentLength];
 //force the control to load data in array
 File.InputStream.Read(imgByte, 0, File.ContentLength);
 }
 // Insert the employee name and image into db
  string conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
  connection = new SqlConnection(conn);
  connection.Open();
  string sql = "INSERT INTO 
  table(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
  SqlCommand cmd = new SqlCommand(sql, connection);
  cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
  cmd.Parameters.AddWithValue("@eimg", imgByte);
  int id = Convert.ToInt32(cmd.ExecuteScalar());
  lblResult.Text = String.Format("Employee ID is {0}", id);

  // Display the image from the database
  Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
 }
 catch
 {
 lblResult.Text = "There was an error";
 }
finally { connection.Close(); }
 }
}

Conclusion: In this article, we learn how to save and convert the image into binary data and save it to the database (MS SQLserver). Also how to retrieve binary data from database and display image in Asp.net C# WebApplication. I.e. converting binary data (bytes) to image

 You can also check these articles:

  1. Upload and Resize image using Dropzone Js Asp.net C#.
  2. Preview Image before upload in jQuery, HTML5 FileReader().
  3. Chart.js Asp.net: Create Pie Chart with database Jquery Ajax C#.
  4. Generic Handler ashx file: Post send JSON data in Asp.net C#.
  5. jQuery Ajax JSON Example in Asp.net with SQL database.

Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time!

Share:    
Satinder Singh

Hi all, am Founder and Author of Codepedia.info, also atypical polyglot programmer from Bombay, India. I have a passion to create, solve, and deploy software applications.
       ForEach ( minute in MyLife ) { myExperience++ ; }



Post Comment


Your email address will not be published. Required fields are marked *