WEBINAR:On-Demand

Sometimes you need to store images in a database instead of as physical files. This sample application will show you how to build a Windows Forms interface that allows you to do the following:

Browse for an image on your hard disk

Load the selected image into a PictureBox control for viewing

Save an image displayed in the PictureBox control to the database

Select an image from a ListBox control, and load it from the database

New Concepts

The new concepts in this article center around the abstract Stream class and how it's used to convert an image file to and from the Image data type that SQL Server uses to store images. Be sure not to confuse the Image data type with the word image, as if to imply that only images can be stored therein. Rather, the Image data type can store anything as variable-length binary data.

A byte array is used to send data to an Image field. Thus, the main question is: How does one convert an image file—whether a JPEG, Bitmap, or other format—into an array of bytes? There are several ways to accomplish this in .NET. One of the easiest ways is to use a concrete implementation of the Stream class. A stream in .NET is essentially an abstraction of a sequence of bytes, whether these bytes came from a file, a TCP/IP socket, a database, or wherever. Stream classes allow you to work with binary data, reading and writing back and forth between streams and data structures (such as a byte array).

Once the image is converted to a byte array, it's saved to a database by using coding.

Creating Database

The first step you have to do is to create a Database table name it Pic, which should contain the two, fields 1: Name 2: Picture. The data Type of the Name field is (nVarChar) and data type of Picture is (Image) in Sql Server 2000.

Note:This Database should be in SQLS erver. I have included the database file in the zip file that you can attach in SQL Server databases. The name of database file is Images_Data.

Browsing for and Displaying an Image

The first task is to find an image on your hard disk. To do this, use an OpenFileDialog object in conjunction with a standard Button control. In the btnBrowse_Click event handler, you can see how this is done. The first few lines of code merely set properties of the OpenFileDialog object.

A pipe-delimited pair of file types is provided to determine the valid file types that can be accessed through the dialog box. Among other properties, you can also set FilterIndex to the default file type that you want to appear in the dialog box's Files Of Type menu. The index is not zero-based, so in this example, Bitmaps will appear as the default.

The dialog box is not actually opened until its ShowDialogmethod is called, which can be combined in an If/Then statement to check which button was pressed and perform follow-on tasks:

If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
With PictureBox1
.Image = Image.FromFile(Me.OpenFileDialog1.FileName)
.SizeMode = PictureBoxSizeMode.CenterImage
End With
End If
Me.Label1.Text = Me.OpenFileDialog1.FileName.ToString

Although an OpenFileDialog object contains an Open button instead of an OK button, there is no DialogResult enumeration for the Open button. Instead, use the OK enumeration. Once it's confirmed that the Open button has been clicked, properties of the PictureBox control are set. Notice how the Image property—which requires an object of type System.Drawing.Image—is assigned. The Image class is abstract and exposes a number of shared methods for working with images, one of which is FromFile. This method creates an Image object from a fully qualified path; although the OpenFileDialog.FileName property might lead you to think that it contains only the file name, it actually has the full path.

Now that your image file is represented by an Imageobject, you can use a stream to convert it to a byte array. In the btnSave_Click event handler, the first line of code creates a MemoryStream object:

Dim ms As New MemoryStream()

A MemoryStream object is simply a stream that uses memory as its backup store instead of some other medium. As a result, a MemoryStream object usually provides better performance. Streams are flexible. You could, for example, have used a FileStream object to open the image file directly and read it in. There are certainly numerous other ways, too. The implementation here, however, is simple and straightforward.

The MemoryStream is then passed as an argument to the Save method, another member of the Image class. You can optionally pass the image format—for example, by accessing the Image's read-only RawFormat property:

picSave.Image.Save(ms, picSave.Image.RawFormat)

The actual byte array conversion comes in the next line. GetBuffer returns an array of unsigned bytes being held by the stream.

Dim arrImage() As Byte = ms.GetBuffer
ms.Close() 'It is good to always close the stream rather than
' to leave it for the garbage collector

The last data-gathering task is to extract the filename from the full path; there is no need to store the entire path in the database:

As you can see, at this point there is nothing new except the use of the SqlDbType.Image enumeration. Set the value of the @Picture parameter to the byte array, and execute the INSERT statement as you would with any other type of data.

Reading an image

From this point forward, you're essentially reversing the process. To display an image, you have to convert it from a byte array to an Image, and then assign it to the PictureBox.Image property:

The SelectedIndex property of the ListBox control is used to to retrieve the contents of the associated Picture field in the DataSet object, which is then explicitly cast to a byte array. Following this, a MemoryStream is created by passing the byte array to its constructor. The last step is to invoke the shared FromStream method to convert the stream contents to an Image, and then assign this to the PictureBox.Image property.

Note: I have generated DataAdapter and Dataset via a wizard, but you can create the Dataset and DataAdapter objects explicitly and perform the required task.

References

Various Microsoft Press Books.

About the Author

Fatima Ahmed

Fatima Ahmed is a B.S. in Computer Sciences and recently working in VC++ and .NET applications. Her interests include teaching, helping others, travelling, writing articles on different topics and studying more and more.

Want to Retrieve image file from Folder and file path stored in SQL database using C#.net in Windows Application

Same Code in VC++

Posted by Sandeep
on 12/17/2012 04:46pm

Hi,
Excellent work.
I am able to use it perfectly in VB.
I am able to store and retreive the images back into picture control.
Now I need the same functionality (store in DB) for word files in Visual c++ code. Could you please help me in this.
Thanks in Advance
Sandeep

vc++ loading images

Posted by karuna
on 02/12/2013 07:20pm

Hi sandeep, i want same code in vc++, can u post the code to me to mail

i try to use mysql but got error pls help

Posted by alccyberspace
on 02/11/2011 09:53am

need help
i got error on this line
[Dim arrayImage() As Byte =_ CType(Me.PayrollDataSet1.Tables(0).Rows(Me.ListBox1.SelectedIndex)("picture"), Byte())]
"Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'."
i change this line
.Parameters.Add(New MySqlParameter("@Picture",_
MySqlDbType."change to Blob instead of Image")).Value = arrayImage

Advertiser Disclosure:
Some of the products that appear on this site are from companies from which QuinStreet receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. QuinStreet does not include all companies or all types of products available in the marketplace.

Thanks for your registration, follow us on our social networks to keep up-to-date