Click here to Skip to main content
15,881,455 members
Articles / Desktop Programming / WPF

An Extension Method for Converting a BitmapImage into a System.Byte with VB 2008

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
14 Apr 2009Ms-PL2 min read 40.2K   333   12   3
Learn how to implement an extension method in Visual Basic 2008 for converting a BitmapImage object into a System.Byte() array

Introduction

Windows Presentation Foundation offers a class called BitmapImage (namespace 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 :-)):

VB.NET
'Instantiates an image
Dim photo As New BitmapImage

'Starts the editing and properties assignment phases
photo.BeginInit()

'UriSource establishes the path of the existing file as an URI
photo.UriSource = New Uri("Photo.jpg", UriKind.Relative)

'StreamSource establishes the file’s source as a stream
photo.StreamSource = New IO.FileStream("Photo.jpg", IO.FileMode.Open)

'End of editing
photo.EndInit()

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:

VB.NET
Imports System.Runtime.CompilerServices
....
....
<Extension()> Module Module1

   ''' <summary>
   ''' Converts a BitmapImage into a System.Byte() array
   ''' </summary>
   ''' <param name="imageSource"></param>
   ''' <returns></returns>
   ''' <remarks></remarks>
   <Extension()> Function ConvertBitmapImageToBytes_
        (ByVal imageSource As BitmapImage) As Byte()
    'Retrieves as a stream the object assigned as a StreamSource
    'to the BitmapImage
    Dim imageStream As IO.Stream = imageSource.StreamSource

    'Declares an empty bytes array
    Dim buffer As Byte() = Nothing

    'if the stream is not empty..
    If imageStream IsNot Nothing And imageStream.Length > 0 Then

    '..via Using..End Using ensures that access to the resource
    'is just limited to our application
        Using imageReader As New IO.BinaryReader(imageStream) 

    'Retrieves as many bytes as long is the stream
             buffer = imageReader.ReadBytes(Convert.ToInt32(imageStream.Length))
        End Using
    End If

    'returns the new bytes array
    Return buffer
   End Function
End Module

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:

VB.NET
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.

History

  • 14th April, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Other
Italy Italy
I'm a Microsoft Visual Basic MVP. I'm an Italian .NET developer and I write articles and books about Visual Basic, Visual Studio LightSwitch, and the .NET technologies.

Check out my blog at: http://community.visual-basic.it/AlessandroEnglish

Comments and Discussions

 
QuestionGreat! Pin
Edward Omowa9-Oct-14 3:47
professionalEdward Omowa9-Oct-14 3:47 
This is great!
GeneralNice Pin
User 2710095-Jul-09 12:26
User 2710095-Jul-09 12:26 
GeneralGrande!!! Pin
DaDoo7023-Apr-09 6:48
DaDoo7023-Apr-09 6:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.