Showing posts with label retrieve binary image from database. Show all posts
Showing posts with label retrieve binary image from database. Show all posts

Monday, 12 May 2014

How to retrieve binary image from database using C# in ASP.NET

Please follow these steps:


Step1: In aspx page add a image control 


<asp:Image ID="img" runat="server"  />

Step2: In code behind add the following code 


protected void Page_Load(object sender, EventArgs e)
        {
            string strCon = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
            SqlConnection con = new SqlConnection(strCon);
            SqlCommand cmd = new SqlCommand("getimage", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            con.Open();
            if (con.State== ConnectionState.Open)
            {
                cmd.ExecuteNonQuery();
                DataTable dt = new DataTable();
                da.Fill(dt);
                byte[] image = (byte[])dt.Rows[0][0];
                img.ImageUrl = "data:image/png;base64 ," + Convert.ToBase64String(image, 0, image.Length);
            }
           

        }

Step3: In Web.config


<add name="DB"
         connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=dbname;Data Source=servername;"
         providerName="System.Data.SqlClient" />