Windows Presentation Foundation offers a class called
System.Windows.Media.Imaging), that allows us to create and/or load images at run-time although it’s optimized for referencing images in XAML code.
My need was uploading an image represented by a
BitmapImage object to a SQL Server database via an Entity Data Model based on the ADO.NET Entity Framework, which receives images as bytes arrays.
Most of solutions you can find on the Internet are related to C#, so I decided to provide a Visual Basic 2008 solution offering an extension method for the
BitmapImage class so that we can see another interesting capability of .NET Framework 3.5.
Using the Code
First of all, let’s start from the
BitmapImage class. The following code snippet instantiates one and assigns an existing image file, as shown in comments (please read them ):
Dim photo As New BitmapImage
photo.UriSource = New Uri("Photo.jpg", UriKind.Relative)
photo.StreamSource = New IO.FileStream("Photo.jpg", IO.FileMode.Open)
Now we have to write a method for converting our result into a
System.Byte() type. As I mentioned before, instead of implementing a custom method inside a class, as we used to do, we can take the advantage of another interesting feature introduced by .NET Framework 3.5: Extension methods. As you can easily understand, they can be successfully used in other situations different from LINQ, even if they've been mainly developed for such technology.
You may remember that in Visual Basic, custom extension methods must reside inside a module which must be decorated with an
<Extension> attribute and that must receive as an argument the type that they're going to extend. According to this sentence, we can write something like the following:
<Extension()> Module Module1
<Extension()> Function ConvertBitmapImageToBytes_
(ByVal imageSource As BitmapImage) As Byte()
Dim imageStream As IO.Stream = imageSource.StreamSource
Dim buffer As Byte() = Nothing
If imageStream IsNot Nothing And imageStream.Length > 0 Then
Using imageReader As New IO.BinaryReader(imageStream)
buffer = imageReader.ReadBytes(Convert.ToInt32(imageStream.Length))
I wrote specific comments inside the code so that reading can be more fluent. Using an XML comment will enable IntelliSense to show a descriptive tooltip each time you'll invoke the method while writing code.
In the end, the following is an example of usage of our new method:
Dim MyArray As Byte() = photo.ConvertBitmapImageToBytes
Points of Interest
You'll now be able to upload images versus your SQL Server databases using Entity Framework with Visual Basic 2008.
- 14th April, 2009: Initial post