Image in C#

How to store and retrieve image from SQL Server to windows form

In C Sharp, Programming, Programming Projects by Baqir Ali

How to store and retrieve image from SQL Server to windows form

Storing and retrieving an image to SQL Server database is not an easy task like storing simple text data in the database. There are multiple steps you should follow to store images in the database. The steps will be discussed in the following sentences.

In order to store images into SQL server database first, we must have a database and table that should store our data.

  1. Go to SQL server management studio and create a database called CodeModes
  2. Run the following code to create a table called EmpPicture
USE [CodeModes]
GO
/****** Object:  Table [dbo].[Image]    Script Date: 1/29/2021 10:50:48 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EmpPicture](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[name] [nvarchar](50) NULL,
	[picture]  NULL,
 CONSTRAINT [PK_Image] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
  1. Now open visual studio create windows form project call it an image, right-click on the Form1 rename it as Employee Image. Change the form text to ‘Image Uploader’.
  2. Drag and drop three labels, three textboxes, two buttons, and a picture box.
  3. Change the properties as follows from the property tab
Store image to SQL SERVER

Set image default image to default picture provided. Double click on the Select image button and type the following code to upload the image to the picture box

 private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog obj = new OpenFileDialog();
                obj.Filter = "Image Files (*.jpg)|*.jpg";
                obj.FilterIndex = 1;
                DialogResult file = obj.ShowDialog();
                if (file == DialogResult.OK)
                {
                    pictureBox1.Image = System.Drawing.Image.FromFile(obj.FileName);
                    this.imgbytes = imageToByteArray(System.Drawing.Image.FromFile(obj.FileName));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }

Conver Image to Array of Bytes

Here you need ‘Byte[] imgbytes’ to convert the image file to an array of bytes as the image datatype is an image in the SQL Server table. The function imageToByteArray() converts the image file to an array of bytes.

Lets name the text boxes as txtSearch,txtId,txtName. Set txtId default value to 0. The logic is as follows if the id is 0, it means a new entry if greater than zero it means to update the data. Let’s code the save button function, double click on the button.     

Double click on the button save

 private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection connection = new SqlConnection(@"Data Source=(Local)\SQLEXPRESS; Database=CodeModes;  integrated security = SSPI");

                if (String.IsNullOrWhiteSpace(txtId.Text) || txtId.Text.Equals("0"))
                {
                    //New Entry
                    if(string.IsNullOrWhiteSpace(txtName.Text))
                    {
                        MessageBox.Show("Please put down name");
                    }
                    else
                    {
                        string name = txtName.Text;
                        System.Drawing.Image imgx;
                        //Create the image object
                        System.Drawing.Image ximgx = pictureBox1.Image;
                        imgbytes = imageToByteArray(ximgx);

                        connection.Open();
                        string sql = "INSERT INTO [EmpPicture](name,[picture])"
                        + "VALUES(@name,@image)";
                        SqlCommand cmd = new SqlCommand(sql, connection);
                        cmd.Parameters.AddWithValue("@name", name);
                        cmd.Parameters.AddWithValue("@image", imgbytes);
                        cmd.ExecuteNonQuery();
                        connection.Close();


                        MessageBox.Show("Done");
                    }
                }
                else
                {
                    //Update
                    if (string.IsNullOrWhiteSpace(txtName.Text))
                    {
                        MessageBox.Show("Please put down name");
                    }
                    else
                    {
                        string name = txtName.Text;
                        int id = Int32.Parse(txtId.Text);
                        System.Drawing.Image imgx;
                        //Create the image object
                        System.Drawing.Image ximgx = pictureBox1.Image;
                        imgbytes = imageToByteArray(ximgx);

                        connection.Open();
                        string sql = "UPDATE [EmpPicture] set name=@name,[picture]=@image where id='" + id + "'";
                        SqlCommand cmd = new SqlCommand(sql, connection);
                        cmd.Parameters.AddWithValue("@name", name);
                        cmd.Parameters.AddWithValue("@image", imgbytes);
                        cmd.ExecuteNonQuery();
                        connection.Close();

                        MessageBox.Show("Done");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

The above code saves the image as well as the name in the database, if the data exists it updates based on the primary key which is id. Now we have to code to search and update the data. Click search textbox and go to Keyup event and press enter. Then type the following code.

 private void txtSearch_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    DataTable dt = null;
                    int id = Int32.Parse(txtSearch.Text);
                    SqlConnection connection = new SqlConnection(@"Data Source=(Local)\SQLEXPRESS; Database=CodeModes;  integrated security = SSPI");
                    connection.Open();
                    using (SqlDataAdapter ds1 = new SqlDataAdapter("SELECT  * from EmpPicture where id='" + id + "'", connection))
                    {
                        DataSet ds = new DataSet();
                        ds1.Fill(ds);
                        dt = new DataTable();
                        dt = ds.Tables[0];
                        connection.Close();
                    }
                    if(dt!=null || dt.Rows.Count>0)
                    {
                        txtId.Text = dt.Rows[0][0].ToString();
                        txtName.Text = dt.Rows[0][1].ToString();
                        this.imgbytes = (Byte[])dt.Rows[0][2];
                        System.Drawing.Image img1 = byteArrayToImage(this.imgbytes);
                        pictureBox1.Image = img1;
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
        public System.Drawing.Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
            return returnImage;
        }

We have to convert from the byte array back to the image so we need another function

The source code is password protected therefore you have to subscribe to our newsletters we will send you the password immediately.

  • First Subscribe With You Email
  • Please share it on social media

Support us by sharing this post

  • Download Now