Click here to Skip to main content
Click here to Skip to main content

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

By , 14 Apr 2009
 

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 :-)):

'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:

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:

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)

About the Author

Alessandro Del Sole
Other
Italy Italy
Member
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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralNicemvpKarl Shifflett5 Jul '09 - 12:26 
Alessandro,
 
Thanks for sharing this. Smile | :)
 
Cheers, Karl
 
» CodeProject 2008 MVP, CodeProject 2009 MVP
 
My Blog | Mole's Home Page |
XAML Power Toys Home Page

Just a grain of sand on the worlds beaches.


GeneralGrande!!!memberDaDoo7023 Apr '09 - 6:48 
Ciao Ale
bello trovarti anche qui ;o)
mi piace quello che scrivi!
Ciao!
D.

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 14 Apr 2009
Article Copyright 2009 by Alessandro Del Sole
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid