Image to DataBase and from DataBase to PictureBox control (C#)
Background
I have been asked about that how would you put an image directly into the database rather saving it in a file system, that's number one. Then second one was, how would you show the same image or any other image in the PictureBox control. To answer these question I thought of writing a blog itself rather than giving conceptual answers. So here we go!!!
Summary
This is a step-by-step tutorial for uploading or adding an image directly into the database and viewing any uploaded image in the PictureBox control in Windows Forms Application.
In VB 6.0 there is no way of saving the binary large object (BLOB) into the database pro-grammatically, it only has the option to show the binary image from database to PictureBox. But over here in this article we will use MemoryStream object from System.IO base class to copy an image from the db to directly into the PictureBox control.
In order to perform this tutorial I have used following
- Microsoft Visual Studio 2010
- Microsoft SQL Server 2008 R2 (you can also use the MS Access for this)
Also I can assume that most of guys knows the Visual C# .NET Windows Forms applications, Binary Large Object(BLOB) in databases, ADO.NET data access.
Let's Start
- As a first step we have to create a table for storing and retrieving our image(s). So let's create the table first using following query
CREATE TABLE tblBLOB ( BLOBID INT IDENTITY NOT NULL, BLOBData IMAGE NOT NULL )Note: For SQL Server users please select/create a database before you run this query
- Next step would be opening the Visual Studio and creating the Windows Forms application project
- Once the project is created the then default windows form will appear in the design mode. Over here you have to add to buttons and one picture box control using ToolBox toolbar. I have renamed the form to BLOBTestForm. After the design is complete it should ideally look like this
Note: I have added a small label for displaying some messages. As of now it not visible, once we will the program and do any action it will show you the appropriate message.
- Once your form design is complete then in the code behind we have to put some code to make it work. We will start with using statements as follows
using System.Data.SqlClient; using System.IO; using System.Drawing.Imaging;
- As database is involved we have make the connection string as well. Following declaration we can put it inside the public class BLOBTestForm : System.Windows.Forms.Form class declaration, configure the connection string as per your settings.
String strConn; strConn = @"Data Source=myServer;Initial Catalog=Example;User Id=myUser;Password=myPassword;";
- Now all necessary things are done, it's time to add some real code on the Button 1(File to Database) click event. This code will read the local image file using FileStream object and then convert it into byte array and pass it to the database using parameterized Command object. Change the file path as necessary.
try { SqlConnection conn = new SqlConnection(strConn); SqlCommand sqlCmd = new SqlCommand("INSERT INTO tblBLOB (BLOBData) VALUES (@BLOBData)", conn); String sBLOBFilePath = @"D:\goal.jpg";//Modify this path as needed. //Read jpg into file stream, and from there into Byte array. FileStream fsBLOBFile = new FileStream(sBLOBFilePath, FileMode.Open, FileAccess.Read); Byte[] bytBLOBData = new Byte[fsBLOBFile.Length]; fsBLOBFile.Read(bytBLOBData, 0, bytBLOBData.Length); fsBLOBFile.Close(); //Create parameter for insert command and add to SqlCommand object. SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary, bytBLOBData.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, bytBLOBData); sqlCmd.Parameters.Add(prm); //Open connection, execute query, and close connection. conn.Open(); sqlCmd.ExecuteNonQuery(); conn.Close(); lblMsg.Text = "File imported successfully into the database."; } catch (Exception ex) { MessageBox.Show(ex.Message); } - Now we have added code for file to database, now we will add the code for database to picture box control. You can add the following code to Button 2(Database to PictureBox) click event. This piece of code retrieves the image bytes from tblBLOB table in the database and puts it into the DataSet object, copies the recently uploaded image into byte array and then converts that into the MemoryStream array, finally we will load this MemoryStream into the image property of PictureBox control.
try { SqlConnection conn = new SqlConnection(strConn); conn.Open(); //Retrieve BLOB from database into DataSet. SqlCommand sqlCmd = new SqlCommand("SELECT BLOBID, BLOBData FROM tblBLOB ORDER BY BLOBID", conn); SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd); DataSet ds = new DataSet(); sqlDA.Fill(ds, "tblBLOB"); int c = ds.Tables["tblBLOB"].Rows.Count; if (c > 0) { //BLOB is read into Byte array, then used to construct MemoryStream, //then passed to PictureBox. Byte[] byteBLOBData = new Byte[0]; byteBLOBData = (Byte[])(ds.Tables["tblBLOB"].Rows[c - 1]["BLOBData"]); MemoryStream stmBLOBData = new MemoryStream(byteBLOBData); pbBLOB.Image = Image.FromStream(stmBLOBData); lblMsg.Text = "File read from the database successfully."; } conn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } - Coding is done, let's compile and Run this application, to do so press F5.
- Once the our Form will appear you first click on File to Database button. So this will add the file into the database. It will look like this
- Once the label shows successful message then you can click on the Database to PictureBox button. This will load the recently added image from the database to PictureBox control. The final output will look like this
That's it.





July 29th, 2011 - 23:18
Cute twitter bird annoying the crap out of me but great article.
October 21st, 2011 - 10:45
Hi,
This blog is good for beginners .But how can we upload the user selected images to DB.
And also how can we displayall in Gridview .
Cheers,
Samantha.
January 23rd, 2012 - 17:40
i hav tried ur following code but m gettin error {keyword not supported InitialCatalog} plz help me out through dis error.
thnx
March 29th, 2012 - 14:05
thank you very much
it is very good topic
April 26th, 2012 - 11:28
Thanxx Dude….
very much….
May 12th, 2012 - 16:18
thnkzz dude …..but i want to do the same thing in webform (asp.net)…..there is no picture box …..how can i display bytes as an image…..plz help me out of dis
June 6th, 2012 - 20:06
I tried this with access 2010. as access don’t have Image type I used oleObject there. But finally I got a error massage saying Parameter is not valid for this line,
pbBLOB.Image = Image.FromStream(stmBLOBData);
What is wrong with me !!! pls help
June 9th, 2012 - 11:06
I have written this code specifically for SQL Server, have not tried with MS Access. If I will find anything I will update my article.
July 14th, 2012 - 19:43
parameter not valid please help
thankyou
July 15th, 2012 - 00:12
i have done this before but i can’t update the image using c#. Can u help me.?
July 16th, 2012 - 22:48
Where are you getting this error. Please elaborate then only I can comment on the same.
July 16th, 2012 - 22:49
If you will follow the steps given in the article then I don’t think that you will get any error. I will add the project file itself in the article so that it will be helpful for you.
July 17th, 2012 - 01:30
the same way i insert the image, i update the image. but after updating the image i can’t retrieve the image, it says invalid image…
July 23rd, 2012 - 17:31
saying Parameter is not valid for this line,
pbBLOB.Image = Image.FromStream(stmBLOBData);
i have cheke the code thare is no mistake and your sorce code is not openin in vs2008
July 23rd, 2012 - 22:50
Hi Bharat,
I have created the project in Visual Studio 2010. Upgrade it or open the code in notepad and copy it in your VS 2008 files. Make sure you change the namespace properly.
Hope this helps!
August 22nd, 2012 - 11:24
Greetz,
Great tut.. But how do i place my lblMsg.Text = “File read from the database successfully.”; on a diff spot..
Thx in advance..
August 23rd, 2012 - 19:42
Actually i when we select file to database button “OpenFileDialog” should come were we can add the image what we want … here only single image is taken from path ..!!
Can u make it in that way … Please reply
August 31st, 2012 - 18:42
hi there i am very impressed with this. I HAVE tried and tested .works wonders. I have about 200 jpeg images which i need to convert into binary data. each one belogs to a specific questionID. IS THERE A WAY TO HAVE IT DONE AT ONE SHOT. SORRY I AM A NEWBIE AT THS.
September 4th, 2012 - 02:36
yogesh ..tis might help
String Pic = MySubID.Text;
String sBLOBFilePath = Pic;
you need to add a Combobox called MySubID on form. (add collection of the path c:\pictures\1234jpg)
you can choose your image there.
October 8th, 2012 - 15:10
Excellent post !!!
Really made my day.
Thanx a lot for sharing.
December 19th, 2012 - 16:20
This is very use full article for beginners.
Same Example Setting the image (Font end) to Bank end Provide them.
January 17th, 2013 - 16:35
Thanks, great article =D
January 30th, 2013 - 07:47
I appreciate your efforts. God richly bless you. AMEN!!!!!
April 7th, 2013 - 21:37
your effort is good.But still I m getting error.’parameter is not valid’.
April 26th, 2013 - 06:07
Wonderful post! We are linking to this particularly
great post on our website. Keep up the great writing.
May 11th, 2013 - 16:01
How to upload image from picturebox.image to database whose datatype is image?
May 11th, 2013 - 16:12
Create a field in the database with “IMAGE” as datatype and use MemoryStream to convert image bytes of PictureBox.Image to database IMAGE type.
Hope this helps!