This morning, my fried buzz me and asking for help. He is creating a customer profile module which contains images like company logo and customer picture. He want to save actual data of the images to a Microsoft SQL server database rather than just storing the file's full path. On this post, using C#, I will try to show you the following:- How to save or store images to MS SQL?
- How to retrieve and display images from MS SQL?
The complete source code of the sample project used on this post can be downloaded from this link.
Storing images to MS SQL Server is easy, first you have to create a field with an Image type. Just copy and paste the following CREATE TABLE script on your query analyzer to create the table.
CREATE TABLE [dbo].[tblImages](
[FullPath] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[MyImageSample] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
On your C# project, add the following controls:
- Textbox for image path
- Textbox for connection string (database)
- Button for saving image to database
- Button for retrieving image from database
- Picture control to display the image
Your form is more or less should look like this:

Now lets do the coding, Add the ReadImageToBytes function written below (this will be called on the Save event):
//Open image file then convert into byte array
byte[] ReadImageToBytes(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;
//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open,
FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
return data;
}
ReadImageToBytes convert the image into bytes that will be stored to database later. Now on your save button, put the following code inside the Click event as shown below:
private void btnSave_Click(object sender, EventArgs e)
{
try
{
//Read Image Bytes into a byte array
byte[] imageSampleData = ReadImageToBytes(txtImagePath.Text);
//Initialize SQL Server Connection
SqlConnection con = new SqlConnection(txtConnectionString.Text);
//Set insert query
string query = "INSERT INTO tblImages (FullPath,MyImageSample) values(@FullPath, @MyImageSample)";
//Initialize SqlCommand object for insert.
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("@FullPath",
(object)txtImagePath.Text));
cmd.Parameters.Add(new SqlParameter("@MyImageSample",
(object)imageSampleData));
//Open connection and execute insert query.
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Error while saving image.", "Error");
}
}
The save button code will insert the byte image into SQL table with image type. You can verify this by opening your table using Query Analyzer or Enterprise Manager.
Now lets double click the retrieve button and add the following code to fetch our stored image:
private void btnRetrieveImage_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(txtConnectionString.Text);
SqlCommand cmd = new SqlCommand();
try
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT Top 1 MyImageSample FROM tblImages"; // for this example only get top record
byte[] Img = (byte[])cmd.ExecuteScalar();
// Convert the image record to file stream and display it to picture control
string str = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(str, FileMode.CreateNew, FileAccess.Write);
fs.Write(Img, 0, Img.Length);
fs.Flush();
fs.Close();
pic1.Image = Image.FromFile(str);
}
catch
{
MessageBox.Show("Error while saving image.", "Error");
}
finally
{
con.Close();
}
}
We're done. Now you have a program than can save and retrieve images. You can also download the complete sample project at mediafire.
For more C# tips and tricks, subscribe now
14 comments:
please help me,i used the code you wrote with a few changes,but i still can't insert a picture in the database.can you tell me why??
Hi emmy. Have you used the sample project included on this article? if not yet, I suggest you check it out first.
Thanks
good article..Thanks a lot :)
Hi!After i have implemented your code, I noticed that,when i run my application, in the debug folder,it creates some files,with no extension.Please tell me what to do. The size of the folder is very large. Thank you!
marius_i - try to clean the folder first then check if the files goes back
same problem. Thanks for your time!:)
how should I put the path in the txtbox???
Thanx dear...its working 101%
cheers...:-)
Wonderful example . This is best example my whole search
work very well thanks ...thanks lot
Verry good example. Thank you for giving knowlegde for beginner programmers
Thanks a lot.
It's usefull :)
Thz a lot for useful coding :)
Thz a lot for best coding :)
thz a lot for useful coding :)
Post a Comment