Sunday, February 8, 2015

Image Storing and Retrieving using C#

  Hi in this blog I am going to explain how to store and retrieve image from Sql Server using C#. In previous blog i explained how to store and retrieve image from sql server using C# aps.net.Here also the steps are sample so now we get into action.


First create a new windows application(File->New Project->Window Form Application).And design it as show in the image below
Note: I am using Tab Control
when the design is completed paste the following code in the App.config file

 <connectionStrings>
    <add name="DBCS" connectionString="Data Source=(local);DataBase=Test;Integrated Security=SSPI"/>
  </connectionStrings>

Now move to the code behind of the form:

And paste the following code for the upload button event handler:

 private void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog1.Filter = "Jpeg Files|*.jpg";
                openFileDialog1.FileName = string.Empty;
                DialogResult result = openFileDialog1.ShowDialog();
                if(result==DialogResult.OK)
                {
                    textBox1.Text = openFileDialog1.FileName;
                    pictureBox1.Load(textBox1.Text);
                    FileStream fs = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read);
                    BinaryReader br = new BinaryReader(fs);
                    Byte[] by = br.ReadBytes((Int32)fs.Length);
                    string strcon = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                    using(SqlConnection conn=new SqlConnection(strcon))
                    {
                        using(SqlCommand cmd=new SqlCommand())
                        {
                            cmd.CommandText="Insert into ImageTable (Title,Data) values(@Name,@Data)";
                            cmd.Parameters.AddWithValue("@Name",Path.GetFileName(openFileDialog1.FileName));
                            cmd.Parameters.AddWithValue("@Data",by);
                            cmd.Connection=conn;
                            conn.Open();
                            cmd.ExecuteNonQuery();
                            conn.Close();
                        }
                    }
                }
            }
            catch(Exception e1)
            {
                MessageBox.Show("Exception:" + e1.ToString());
            }
        }

After that paste the following code for the submit button event handler:

private void bntSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                string constr = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                MemoryStream ms = new MemoryStream();
                using(SqlConnection conn=new SqlConnection(constr))
                {
                    using(SqlCommand cmd=new SqlCommand())
                    {
                        cmd.CommandText = "select Data from ImageTable where ID="+textBox2.Text.Trim()+"";                      
                        cmd.Connection = conn;
                        conn.Open();
                        SqlDataReader rdr = cmd.ExecuteReader();
                        byte[] by=null;
                        while (rdr.Read())
                        {
                            by = (byte[])rdr[0];                          
                        }
                        ms.Write(by, 0, by.Length);
                        Bitmap bmp = new Bitmap(ms);
                        pictureBox2.Image = bmp;
                        conn.Close();
                    }
                }

            }
            catch (Exception e1)
            {
                MessageBox.Show("Exception:" + e1.ToString());
            }
        }

Sample Output Screen:

Image Upload

Image Download:



Download the full source code from here.

Click here for my previous blog

Happy coding.


No comments:

Post a Comment