Inserting and Retrieving images from SQL Server Database using C#
I think storing images in a database can save a developer loads of time and can ease his life while dealing with visuals, either creating a local application or a web application. Think of storing your images of a certain web application in a database instead in a directory exits somewhere in a cloud which one-a bit headache and second-completely transparent with respects to its location. So, here we are, I am going to create here a local application through which we can insert and retrieve an image using c# from a sql server 2005 database.
First I created a database named TestImage in which I created a table called test_table holding two columns id_image(datatype: nvarchar) and pic(datatype: image).
Second create a new project in visual studio, select windows application, language c# and name it as TestImage. Now using you toolbox, drop two labels, a textbox, a combo box, three buttons and two picture boxes on your win from, you UI must be looking something like the image below:
The first picture box will only displays the image you are going to save in your database providing some id in the textbox (I used this to just recall the image from database) once an image is loaded on the clicking event of Store button we are going to insert that image with provided ID into the database and the combo box will load itself with all available IDs in our database. By selecting an id we and clicking Retrieve the respective image will be shown in the second picture box.
So, now right click on your form and select view code.
Here declare a global string
a data adapter
and a dataset
you will also require to use System.IO and System.Data.SqlClient
now we need to create a method to insert our image into the database and second method to retrieve all images. I named the method inserting my image into the database as update() and to retrieve my images I named my method as connection(). Now update() uses filestream to convert the image into binary data since image datatype in SQL Server 2005 use to store binary data in its image datatype. While connection() simply convert that binary data to an image using identical technique for us. Code for both the methods is:
//use filestream object to read the image.
//read to the full length of image to a byte array.
//add this byte as an oracle parameter and insert it into database.
//proceed only when the image has a valid path
if (imagename != "")
fs = new FileStream(@imagename, FileMode.Open, FileAccess.Read);