Saturday, December 11, 2010

Storing Pictures in MS SQL Server in a C# Windows Forms Application & retrieving it.

In a previous Post I have shown how to handle Images in SQL Server through ASP.NET. There is another Post  that does the same for PHP and MySql. In this post we will store a picture via a C# Windows application and also retrieve it and display it in a Picture Box.

Here is how you create the tables : -

create table Pictures(PictureName varchar(50) primary key,Picture varbinary(max) not null)

Start a new Windows Application in Visual Studio. Open Server Explorer and open the database. Create a DataSet and drag the table to the DataSet.




Create two queries:-
1) The Insert Query
INSERT INTO Pictures  values(@PictureName,@Picture).
Let's name it InsertAPicture
2) The Select Query which is a Scalar Query 
SELECT Picture  FROM Pictures where PictureName=@PictureName
Let's call it GetThePicture

Create a Windows form and add a OpenFileDialog, a PictureBox, some TextBoxes and Labels.
Here is the form.
Here is the code that loads a picture from a file to the picture box

The Button Click Handler
   private void button1_Click(object sender, EventArgs e)
        {
            try
            {
              openFileDialog1.FileName = "";
              openFileDialog1.Filter = "All Pictures|*.bmp;*.jpg;*.jpeg;*.wmf;*.png|All Files|*";
              openFileDialog1.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Picture Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

The File Dialog OK Handler
        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            try
            {
                picFromFile.Image = System.Drawing.Image.FromFile(openFileDialog1.FileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Picture Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }




And this is the Code for saving the Picture in the PictureBox to the Database.

 private void button2_Click(object sender, EventArgs e)
        {
            try
            {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
           picFromFile.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] b = new byte[(int)ms.Length];
            ms.Position = 0;
            ms.Read(b, 0, (int)ms.Length);
           DataSet1TableAdapters .PicturesTableAdapter da=new Storing_and_Retrieving_Pictures.DataSet1TableAdapters.PicturesTableAdapter ();
           da.InsertAPicture(txtPictureName.Text, b);
           MessageBox.Show(this, "Picture Inserted", "Picture Application", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Picture Application", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }
 


Here is the Code for retrieving the Picture from the Database.
private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet1TableAdapters.PicturesTableAdapter da = new Storing_and_Retrieving_Pictures.DataSet1TableAdapters.PicturesTableAdapter();
                byte[] b = da.GetThePicture(txtSearchName.Text);
                System.IO.MemoryStream ms = new System.IO.MemoryStream(b);
                picFromDatabase.Image  = new Bitmap(ms);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Picture Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Storing_and_Retrieving_Pictures
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void picFromFile_Click(object sender, EventArgs e)
        {

        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
              openFileDialog1.FileName = "";
              openFileDialog1.Filter = "All Pictures|*.bmp;*.jpg;*.jpeg;*.wmf;*.png|All Files|*";
              openFileDialog1.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Picture Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            try
            {
                picFromFile.Image = System.Drawing.Image.FromFile(openFileDialog1.FileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Picture Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
           picFromFile.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] b = new byte[(int)ms.Length];
            ms.Position = 0;
            ms.Read(b, 0, (int)ms.Length);
           DataSet1TableAdapters .PicturesTableAdapter da=new Storing_and_Retrieving_Pictures.DataSet1TableAdapters.PicturesTableAdapter ();
           da.InsertAPicture(txtPictureName.Text, b);
           MessageBox.Show(this, "Picture Inserted", "Picture Application", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Picture Application", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet1TableAdapters.PicturesTableAdapter da = new Storing_and_Retrieving_Pictures.DataSet1TableAdapters.PicturesTableAdapter();
                byte[] b = da.GetThePicture(txtSearchName.Text);
                System.IO.MemoryStream ms = new System.IO.MemoryStream(b);
                picFromDatabase.Image  = new Bitmap(ms);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Picture Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
 


app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="Storing_and_Retrieving_Pictures.Properties.Settings.HypatiaConnectionString"
            connectionString="Data Source=.\hypatia;Initial Catalog=Hypatia;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>

</configuration>


Form1.Designer.cs


namespace Storing_and_Retrieving_Pictures
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.picFromDatabase = new System.Windows.Forms.PictureBox();
            this.button1 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.txtPictureName = new System.Windows.Forms.TextBox();
            this.button2 = new System.Windows.Forms.Button();
            this.label2 = new System.Windows.Forms.Label();
            this.txtSearchName = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.button3 = new System.Windows.Forms.Button();
            this.picFromFile = new System.Windows.Forms.PictureBox();
            this.label4 = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.picFromDatabase)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.picFromFile)).BeginInit();
            this.SuspendLayout();
            //
            // openFileDialog1
            //
            this.openFileDialog1.FileName = "openFileDialog1";
            this.openFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.openFileDialog1_FileOk);
            //
            // picFromDatabase
            //
            this.picFromDatabase.Location = new System.Drawing.Point(356, 234);
            this.picFromDatabase.Name = "picFromDatabase";
            this.picFromDatabase.Size = new System.Drawing.Size(129, 137);
            this.picFromDatabase.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.picFromDatabase.TabIndex = 0;
            this.picFromDatabase.TabStop = false;
            this.picFromDatabase.Click += new System.EventHandler(this.picFromFile_Click);
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(824, 204);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(115, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "Get Picture from File";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(68, 39);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(71, 13);
            this.label1.TabIndex = 2;
            this.label1.Text = "Picture Name";
            //
            // txtPictureName
            //
            this.txtPictureName.Location = new System.Drawing.Point(157, 36);
            this.txtPictureName.Name = "txtPictureName";
            this.txtPictureName.Size = new System.Drawing.Size(169, 20);
            this.txtPictureName.TabIndex = 3;
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(175, 73);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(114, 23);
            this.button2.TabIndex = 4;
            this.button2.Text = "Save To Database";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(71, 213);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(72, 13);
            this.label2.TabIndex = 5;
            this.label2.Text = "Search Name";
            //
            // txtSearchName
            //
            this.txtSearchName.Location = new System.Drawing.Point(157, 206);
            this.txtSearchName.Name = "txtSearchName";
            this.txtSearchName.Size = new System.Drawing.Size(169, 20);
            this.txtSearchName.TabIndex = 6;
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(356, 211);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(112, 13);
            this.label3.TabIndex = 7;
            this.label3.Text = "Picture from Database";
            this.label3.Click += new System.EventHandler(this.label3_Click);
            //
            // button3
            //
            this.button3.Location = new System.Drawing.Point(157, 253);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(151, 23);
            this.button3.TabIndex = 8;
            this.button3.Text = "Get Picture from Database";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
            //
            // picFromFile
            //
            this.picFromFile.Location = new System.Drawing.Point(824, 51);
            this.picFromFile.Name = "picFromFile";
            this.picFromFile.Size = new System.Drawing.Size(129, 137);
            this.picFromFile.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.picFromFile.TabIndex = 0;
            this.picFromFile.TabStop = false;
            this.picFromFile.Click += new System.EventHandler(this.picFromFile_Click);
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(824, 28);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(112, 13);
            this.label4.TabIndex = 7;
            this.label4.Text = "Picture from Database";
            this.label4.Click += new System.EventHandler(this.label3_Click);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(974, 412);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.txtSearchName);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.txtPictureName);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.picFromFile);
            this.Controls.Add(this.picFromDatabase);
            this.Name = "Form1";
            this.Text = "Storing and Retrieving Pictures";
            ((System.ComponentModel.ISupportInitialize)(this.picFromDatabase)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.picFromFile)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.OpenFileDialog openFileDialog1;
        private System.Windows.Forms.PictureBox picFromDatabase;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txtPictureName;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txtSearchName;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.PictureBox picFromFile;
        private System.Windows.Forms.Label label4;
    }
}

Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Storing_and_Retrieving_Pictures
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}




In the next few blogs we shall discuss the storing and retrieving of pictures in Java & Oracle.









2 comments:

  1. Thanks for that.i like to request here. I would like to know how to create table,storing html links with MS SQL. In chance did you know how to build search engine like google using MS SQL and Asp.net. Please post for that. Thank you very much.

    ReplyDelete
  2. very good explanation.thank you sir.

    ReplyDelete