Store or save images in SQL Server database using C#

Store Images in SQL Server

This sample code explains you how you can store or save images in SQL Server database using C#.

It uses ADO.Net System.Data.SqlClient namespace.

Images can be stored in sql server using Sql parameters.

How to Store or Save Image in SQL Server table

To store an image in to sql server, you need to read image file into a byte array. Once you have image data in byte array, you can easily store this image data in sql server using sql parameters. Following code explains you how to do this.

        
private void cmdSave_Click(object sender, EventArgs e)
{
 try
 {
 //Read Image Bytes into a byte array
 byte[] imageData = ReadFile(txtImagePath.Text);

 //Initialize SQL Server Connection
 SqlConnection CN = new SqlConnection(txtConnectionString.Text);

 //Set insert query
 string qry = "insert into ImagesStore (OriginalPath,ImageData) _
 values(@OriginalPath, @ImageData)";

 //Initialize SqlCommand object for insert.
 SqlCommand SqlCom = new SqlCommand(qry, CN);

 //We are passing Original Image Path and 
 //Image byte data as sql parameters.
 SqlCom.Parameters.Add(new SqlParameter("@OriginalPath", 
 (object)txtImagePath.Text));
 
 SqlCom.Parameters.Add(new SqlParameter("@ImageData", 
 (object)imageData));

 //Open connection and execute insert query.
 CN.Open();
 SqlCom.ExecuteNonQuery();
 CN.Close();

 //Close form and return to list or images.
 this.Close();
 }

Following code explains how to read image file in to a byte array.

        
 //Open file into a filestream and 
 //read data in a byte array.
 byte[] ReadFile(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);

 //When you use BinaryReader, you need to 

 //supply number of bytes to read from file.
 //In this case we want to read entire file. 

 //So supplying total number of bytes.
 data = br.ReadBytes((int)numBytes);
 return data;
 }

How to read image data bytes from SQL Server table

To read images from SQL Server, prepare a dataset first which will hold data from SQL Server table. Bind this dataset with a gridview control on form.

        
 void GetImagesFromDatabase()
 {
 try
 {
 //Initialize SQL Server connection.
 SqlConnection CN = new SqlConnection(txtConnectionString.Text);

 //Initialize SQL adapter.
 SqlDataAdapter ADAP = new SqlDataAdapter("Select * from ImagesStore", CN);

 //Initialize Dataset.
 DataSet DS = new DataSet();

 //Fill dataset with ImagesStore table.
 ADAP.Fill(DS, "ImagesStore");

 //Fill Grid with dataset.
 dataGridView1.DataSource = DS.Tables["ImagesStore"];
 }
 catch(Exception ex)
 {
 MessageBox.Show(ex.ToString());
 }
 }

Once you have image data in grid, get image data from grid cell. Alternatively you can also get image data from Dataset table cell.

        
 //Store image to a local file.
 pictureBox1.Image.Save("c:\test_picture.jpg",
System.Drawing.Imaging.ImageFormat.Jpeg);

If you want you can extend this code to save image from Picture Box to a local image file.

        
 //Store image to a local file.
 pictureBox1.Image.Save("c:\test_picture.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);


Points of Interest

If you see frmImageStore in design mode, I have placed picturebox1 into a panel. This panel's AutoScroll property is set to True and SizeMode property of PictureBox1 is set to True. This allows picturebox to resize itself to the size of original picture. When picturebox's size is more than Panel1's size, scrollbars becomes active for Panel.

How to download and run program

  • Download source zip file from here . Extract in a folder.
  • Restore database from SQL Database sub folder.
  • If some how you can not restore provided database, you can generate necessary table using script provided in SQL Database directory.
  • Open solution and change connection string on frmImagesStore form.

Requirements

Visual Studio.Net 2005

.Net Framework 2.0

MS SQL Server 2000 database or MS SQL Server 2005 database.

SpecialĀ  Notes

I have published this article on codeproject.com as well. Here is the link to this article.

http://www.codeproject.com/useritems/Store_images_in_SQL_Serve.asp


Comments/Questions

hi thanks for nice article.
but can u tell me how to create the tables in sql server.which datatype i hav to use while creating the table?
=> thams (Friday 25-Apr-08 02:05 AM)
Reply
Create table table_name(i int,names varchar(20),address(varchar(20))


This is the way to create table in database
=> subaganesh (Thursday 22-May-08 04:36 AM)
Reply
can u please explain what to store in txtImagePath.Text
=> jyoti (Tuesday 16-Sep-08 01:37 AM)
Reply
Super..........

it worked perfect. so you continue this type issue in net!!!

Thankssssssssssssssss.......

=> Loganathan (Friday 13-Jun-08 02:02 AM)
Reply
hi, this is mukhtar.
Thank you very much for this code.
bye takecar :)
=> SARDAR MUKHTAR ALI KHAN (Thursday 19-Jun-08 06:57 AM)
Reply
What to write in the connection string text box? I am confused :( Kindly help me by giving an example.
=> Holy Harem (Saturday 26-Jul-08 12:54 AM)
Reply
String s="Server=servername;database=databasename;uid=sa;pwd=pwd;";




use this connection string for ur connection string textbox ...


Thanks
Suba(www.computerleaders.co.nr)
=> Suba Ganesh (Sunday 27-Jul-08 11:43 PM)
Reply
Thanks Suba :) I already explored it, but still thank you very much ...
=> Holy Harem (Monday 04-Aug-08 01:00 AM)
Reply
Ok ok n thanks
=> Suba (Monday 04-Aug-08 03:54 AM)
Reply
Suba!

How r u?

Hope to see u in the best of ur health and spirits,

Can u plz help me in solving the following problem:-
I have used this code in an image editor. When I open image from hard disk, all edit functions work perfectly but when I open image from database and try to edit it, no function works :( Kindly help me out...

Regards,
=> Holy Harem (Wednesday 06-Aug-08 11:55 PM)
Reply
Ya am fine.....Holy i cant get ur question ...can u plz send me the code t my mail ...clearly



My ID:endrum18rediffmail.com
=> Suba Ganesh (Thursday 07-Aug-08 02:32 AM)
Reply
Hi, I want to same thing in VB6 using SQL Sever. Please help me.
=> Kashif (Tuesday 12-Aug-08 01:50 AM)
Reply
hi,
hru,
how to insert imageurl in database(SQL Server)
and retrive that imageurl in crystalreport10 and that url
show the image type
how get this.
pls help me
=> vanaja (Friday 29-Aug-08 07:34 AM)
Reply
How to create a table using array data type in one of its field? Or any alternative way to store array in a table.
=> Shastri (Wednesday 24-Sep-08 01:55 AM)
Reply
Thats a very nice code but i want the same thing in VB6 using SQL Server.
=> Kashif (Friday 26-Sep-08 12:28 AM)
Reply
I need help
=> Jon Berg (Monday 13-Oct-08 05:33 AM)
Reply
Great.! Thanks LOTS!
=> Jeremy (Wednesday 29-Oct-08 11:40 AM)
Reply
hi could u tell me whc datatype i have to use in sql for image save and and can u explain the readfile function
pls i will be very obliged
thx and regards
Dinesh sharma
=> Dinesh sharma (Tuesday 16-Dec-08 07:44 AM)
Reply

Posted: 3 years 10 months ago by codeKenn #288
codeKenn's Avatar
shabdar.... u r really amazing... fank u so much for d article, d forum and d website shabdar.org, more greese to ur elow
Posted: 5 years 9 months ago by raijia31 #109
raijia31's Avatar
hi..., i am new to C# programming.., may i ask if where does the ReadFile variable comes from..because my program gives me an error that the name 'ReadFile' does not exist in the current context.., can you tell how why does this happen? and how to resolve this error?... please.

Thank you very much