Adding and retrieving Images from a SQL Server Table

This article describes the process to add and retrieve images from a SQL Server table using ADO.NET. You can possibly have an entry form that will allow the user to choose what operation he wants to do: add or view images. Depending on the option chosen you can display the relevant form.
 
To add images to the form, the following procedure can be used. A textbox can be displayed on the form to accept the desired image filename from the user. This file must be existing on the local machine and can be chosen using an OpenFileDialog instance.
  1. OpenFileDialog oFileDialog1 = new OpenFileDialog();  
  2. oFileDialog1.InitialDirectory = "c:\\";  
  3. oFileDialog1.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";  
  4. oFileDialog1.FilterIndex = 1;  
  5. oFileDialog1.RestoreDirectory = true;  
  6. if (oFileDialog1.ShowDialog() == DialogResult.OK) {  
  7.       if (oFileDialog1.FileName != null) {  
  8.             txtPic.Text = oFileDialog1.FileName;  
  9.       }  
  10. }  
Once the image file name has been given, it can be passed to another method to convert the underlying image to stream format.
  1. filename = txtPic.Text;  
  2. byte [] content = ImageToStream(fileName);  
  3. StoreImage(content);  
The user-defined method ImageToStream will create a MemoryStream instance based on the given file and then convert it into a byte array.
  1. private byte[] ImageToStream(string fileName) {  
  2.       Bitmap image = new Bitmap(fileName);  
  3.       MemoryStream stream = new MemoryStream();  
  4.       image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);  
  5.       return stream.ToArray();  
  6. }  
The method StoreImage will create parameters and populate them with values so that they can be used with an insert command to add the image and its details to the table. It is assumed that the table has 3 fields - image, filename and image number. Given the byte array as input, this method constructs an Insert command and creates 3 parameters for the 3 field values. The image number is an incremental value which is calculated by getting the last value and adding 1 to it. If the table is empty, it begins with 1.
  1. private void StoreImage(byte[] content) {  
  2.       if (MainForm.conn.State.Equals(ConnectionState.Closed))  
  3.             MainForm.conn.Open();  
  4.       try {  
  5.             SqlCommand insert = new SqlCommand("Insert into Images values (@image, @picid,@name)", MainForm.conn);  
  6.             int id;  
  7.             try {  
  8.                   SqlCommand selectcmd = new SqlCommand("Select max(picid) from images", MainForm.conn);  
  9.                   id = (int) selectcmd.ExecuteScalar() + 1;  
  10.             } catch (Exception ex) {  
  11.                   Console.WriteLine(ex.StackTrace);  
  12.                   id = 1;  
  13.             }  
  14.             SqlParameter picParameter = insert.Parameters.Add("@picid", SqlDbType.Int);  
  15.             picParameter.Value = id;  
  16.             picParameter.Size = 4;  
  17.             SqlParameter imageParameter = insert.Parameters.Add("@image", SqlDbType.Binary);  
  18.             imageParameter.Value = content;  
  19.             imageParameter.Size = content.Length;  
  20.             SqlParameter nameParameter = insert.Parameters.Add("@name", SqlDbType.Char);  
  21.             nameParameter.Value = fileName;  
  22.             nameParameter.Size = fileName.Length;  
  23.             insert.ExecuteNonQuery();  
  24.             MessageBox.Show("Image has been added successfully");  
  25.             success = true;  
  26.       } catch (Exception ex) {  
  27.             MessageBox.Show(ex.Message.ToString());  
  28.             MessageBox.Show(ex.StackTrace.ToString());  
  29.       } finally {  
  30.             MainForm.conn.Close();  
  31.       }  
  32. }  
 
If you try to look at the contents of the image field in the Sql Server table, you will find that it is stored in binary format.
 
On loading the View form, a listbox can be populated with the existing image file names from the table. The user can then select a particular image file name from the list to display it.
  1. MainForm.conn.Open();  
  2. SqlCommand cmd = new SqlCommand("Select picname from images", MainForm.conn);  
  3. SqlDataReader content = cmd.ExecuteReader();  
  4. while (content.Read()) {  
  5.       lstImages.Items.Add(content.GetString(0));  
  6. }  
  7. content.Close();  
The user selection from the listbox can be captured using SelectIndexChanged event.
  1. private void lstImages_SelectedIndexChanged(object sender, System.EventArgs e) {  
  2.       image = lstImages.SelectedItem.ToString();  
  3. }  
To view images, the following code can be used:
  1. if (MainForm.conn.State.Equals(ConnectionState.Closed))  
  2.       MainForm.conn.Open();  
  3. SqlCommand cmd = new SqlCommand("Select picture from images where picname like '" + image + "';", MainForm.conn);  
  4. byte[] content = (byte[]) cmd.ExecuteScalar();  
  5. try {  
  6.       MemoryStream stream = new MemoryStream(content);  
  7.       pic1.Image = Image.FromStream(stream);  
  8. catch (Exception ex) {  
  9.       MessageBox.Show(ex.Message.ToString());  
  10.       MessageBox.Show(ex.StackTrace.ToString());  
  11. }  
 
As you can see, the procedure is quite simple.


Similar Articles