How to store and Retrieve Images in Database using C#

We Programmers, daily use database for different work but the main thing is that we only save text and other stuff but we never post and save images in the databse
To save the images in the database we should have to first convert them to the bytes and when they would be retrived the method will be opposite first the bytes stored in the database will be coverted back to the bytes and then to image the sample code is as following

private void btnLoad_Click(object sender, EventArgs e)
{
try
{

FileDialog fldlg = new OpenFileDialog();

//specify your own initial directory

fldlg.InitialDirectory = @”:D\”;

//this will allow only those file extensions to be added

fldlg.Filter = “Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif”;

if (fldlg.ShowDialog() == DialogResult.OK)
{

imagename = fldlg.FileName;

Bitmap newimg = new Bitmap(imagename);

//pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

//pictureBox1.Image = (Image)newimg;
MessageBox.Show(“Image Loaded”);

}

fldlg = null;

}

catch (System.ArgumentException ae)
{

imagename = ” “;

MessageBox.Show(ae.Message.ToString());

}

catch (Exception ex)
{

MessageBox.Show(ex.Message.ToString());

}
}

private void retrive_Click(object sender, EventArgs e)
{
DataTable dataTable = dset.Tables[0];

//if there is an already an image in picturebox, then delete it

if (pictureBox2.Image != null)
{

pictureBox2.Image.Dispose();

}

//using filestream object write the column as bytes and store
//it as an image

FileStream FS1 = new FileStream(“image.jpg”, FileMode.Create);

foreach (DataRow dataRow in dataTable.Rows)
{

if (dataRow[0].ToString() == comboBox1.SelectedItem.ToString())
{

byte[] blob = (byte[])dataRow[1];

FS1.Write(blob, 0, blob.Length);

FS1.Close();

FS1 = null;

pictureBox2.Image = Image.FromFile(“image.jpg”);

pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;

pictureBox2.Refresh();

}

}
}
}
}

Govt. College University Lahore
Computer Science Dept.
Author Name : M Hashim Bajwa
Roll No: 063-bscs-2010
Section: A