Save and retrieve image from SQL 2005 in ASP.Net

How to save image in database

Data base design:

  1. Create SQL table with the name of "ImageExample" and the create column with image datatype as Image.

    sql table

Store Image in Grid:

To store image in database first we have to open and read the file and convert the file into byte array. For saving to database

The C# coding to save image:

    SqlConnection con = new SqlConnection("Connection string");
    SqlCommand oc=new SqlCommand("insert into TableName values(@Image)",con);
    string path=@"Path\imagename.JPG";
                                FileStream fs=new FileStream(path,FileMode.Open,FileAccess.Read);
                                BinaryReader br=new BinaryReader(fs);
                                 FileInfo fi=new FileInfo(path);
                                byte[] imagedata = br.ReadBytes((int)fi.Length);
                                oc.Parameters.Add("@Image", imagedata);

Retrieve image from database using handler.

  1. Right click on solution explorer and select add new item.In that select hanler.ashx and rename as ImageHandler.ashx

Code used in Imagehandler.aspx

class Handler1 : IHttpHandler
        public void ProcessRequest(HttpContext context)
            string imageid = context.Request.QueryString["Image"];
            SqlConnection con = new SqlConnection("Connectionstring");
            SqlCommand command = new SqlCommand("select Image from ImageExample", con);
            SqlDataReader dr = command.ExecuteReader();
        public bool IsReusable
                return false;

Code used in aspx page

asp:GridView ID="GridView1" runat="server" Width="500px" AutoGenerateColumns="false">
           <asp:TemplateField HeaderText="Image">
           <asp:Image ID="Image" runat="server" ImageUrl='<%#"ImageHandler.ashx"%>'/>

Code used in Retrieve image using C#

   SqlConnection con = new SqlConnection("Connnection string");
   SqlCommand oc = new SqlCommand("Select * from ImageExample", con);
   SqlDataAdapter da = new SqlDataAdapter(oc);
   DataTable dt = new DataTable();
   GridView1.DataSource = dt;

Similar Articles