Home > DeveloperSection > Blogs > Save image in SqlServer using C#.

Save image in SqlServer using C#.

Posted by  Awadhendra Tiwari
on    May-21-2011 8:45 AM

C# C# 
Ratings:
4 Comment(s)
 23795  View(s)
Rate this:

Save image in Sql Server using C#

In this blog I will tell you that how to save image in Sql Server using c#. Here I will give you necessary steps to store image in sql server.

1)      Before we are starting to make application in C# firstly we need to create a table in sql server where we store out image. Here I will create a table named ImageTable in which I will store image. ImageTable contains two column one is imageID which will store id of image in image table. And other column which have name imageData is stored image in format of binary.

Here I will provide a sample sql code snippet to create ImageTable

create table ImageTable

(

     imageID int,

     imageData image

)

2)      Now import System.Data.SqlClient namespace in your project. This namespace provide you all necessary classes and interfaces which is necessary to establish connection to SqlServer.

3)      Create following methods and call it according to your requiremnt.

/// <summary>

        /// On click event of browse button write down following code. This

        /// Will display a open file dialog box which will ask to choose you

        /// image and will store path of image in textbox.

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void button1_Click(object sender, EventArgs e)

        {

            OpenFileDialog ofd = new OpenFileDialog();

            if (DialogResult.OK == ofd.ShowDialog())

            {

                textBox1.Text = ofd.FileName;   //storing path of image in textbox.

            }

        }

        /// <summary>

        /// On the click of SaveButton call saveImageInDataBase(int imgId) method

        /// which will save image in database.

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void button2_Click(object sender, EventArgs e)

        {

            saveImageInDataBase(1);

        }

        /// <summary>

        /// This is a required method which will save image in database.

        /// </summary>

        /// <param name="imageID"></param>

        public void saveImageInDataBase(int imageID)

        {

            byte[] imageData = ReadImageFile(textBox1.Text);    //This nethod returns image in byte array format.

            SqlConnection con = new SqlConnection();

            con.ConnectionString = "Data Source=aaaa;User ID=sa;Password=abcd;Initial Catalog=Workbook";  //provide connection string of your server.

            con.Open();   //open connection to server.

            string query = "insert into ImageTable values(@imageId,@imageData)";     //create a query variable.

            SqlCommand cmd = new SqlCommand(query, con);          //create a sqlcommand object.

            cmd.Parameters.Add(new SqlParameter("@imageId", imageID));    //add first parameters.

            cmd.Parameters.Add(new SqlParameter("@imageData", imageData));    //add second parameters.

            int rows = cmd.ExecuteNonQuery();         //execute query.

            if (rows > 0)

                MessageBox.Show("Image saved.");

            else

                MessageBox.Show("Unable to save image.");

            con.Close();

        }

        /// <summary>

        /// This method will converts image in byte array format and returns to its caller.

        /// use System.IO namespace regarding streaming concept.

        /// </summary>

        /// <param name="imageLocation"></param>

        /// <returns></returns>

        public byte[] ReadImageFile(string imageLocation)

        {

            byte[] imageData = null;

            FileInfo fileInfo = new FileInfo(imageLocation);

            long imageFileLength = fileInfo.Length;

            FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);

            BinaryReader br = new BinaryReader(fs);

            imageData = br.ReadBytes((int)imageFileLength);

            return imageData;

        }

    }


very good

By aken H on   3 years ago

hi  Awadhendra Tiwari

    i appreciation you write technical article.

thanks for your article.


Save image in Sql Server using C#

By John Smith on   3 years ago
nice blog...

Save image in Sql Server.

By James Smith on   3 years ago
Hey Awadhendra,
Good one..

Thanks for sharing it with us.

nice article

By shwetank suthar on   one year ago
n1... :)

good one.















Don't want to miss updates? Please click the below button!