Derik Whittaker

Syndication

News


Converting StorageFiles (png) to a Byte[] in order to display as an Image in WinRT (C#)

When you are building Metro Applications it will be very common that your application will have image (.png) files stored in local isolated storage and that you will want to show these images to the users inside your application.  In this post i am going to walk you though how to access these stored files and how to show them inside your XAML application.

Step 1: How to access the Storage File

var packageLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
var assetsFolder = await packageLocation.GetFolderAsync("Assets");
StorageFile myImage = await assetsFolder.GetFileAsync("myFile.png");

// We now have our StorageFile to work with

In the above code we are going to get the point to the current installed location.  Once we have that we are going to get the folder which holds our file, in our case Assets.  Once we have our folder we want to get the file via the GetFileAsync.  Once this completes we now have our pointer to StorageFile to work with.

*** NOTE ***
If the folder/files are not found then an exception will be thrown so make sure you take this into account

Step 2: How to convert the file to a Byte[]

var bytes = await GetBtyeFromFile(myImage);

// This is the method to convert the StorageFile to a Byte[]        
private async Task GetBtyeFromFile(StorageFile storageFile)
{
    var stream = await storageFile.OpenReadAsync();

    using (var dataReader = new DataReader(stream))
    {
        var bytes = new byte[stream.Size];
        await dataReader.LoadAsync((uint)stream.Size);
        dataReader.ReadBytes(bytes);

        return bytes;
    }
}

In the code above we are going to open the StorageFile up and get back the stream.  Once we have the stream we will want to get the byte[] via the DataReader

Step 3: How to convert the Byte[] to an Image

public ImageSource Image
{
    get
    {
        if (_image == null && bytes != null )
        {
            var stream = new MemoryStream(bytes);
            var randomAccessStream = new MemoryRandomAccessStream(stream);

            var bi = new BitmapImage();
            bi.ImageFailed += (s, o) =>
            {
		// This event is optional and is used to let us know if something went wrong
                var m = "Failure;
            };

            bi.SetSource(randomAccessStream);

            _image = bi;
        }

        return _image;
    }
}

The code above is a property in my ViewModel.  This property will convert the byte[] to an image in real time. 

*** NOTE ***
I have hooked up the .ImageFailed event simply to know if something went wrong.  This will be fired if the loading of the randomAccessStream failed.

The MemoryRandomAccessStream class came from this post

Step 4: How to bind the image to the UI

<Image Height="75" Width="75" Margin="5" Source="{Binding Image}" />

The above is simply the XAML needed to bind the Image Property in our ViewModel above to the UI.

As you can see there is a bit of code needed to go from StorageFile to Byte[] to ImageSource but as you can also see it is not too hard.

Till next time,


Posted 07-06-2012 9:54 AM by Derik Whittaker
Filed under: , ,

[Advertisement]

Comments

Damien Guard wrote re: Converting StorageFiles (png) to a Byte[] in order to display as an Image in WinRT (C#)
on 07-06-2012 1:37 PM

<Image Src="/Assets/myFile.png" />

[)amien

rob_dev wrote Converting a byte array to image in WinRT
on 09-10-2012 8:57 PM

Converting a byte array to image in WinRT

rob_dev wrote Converting a byte array to an image in WinRT
on 09-10-2012 9:00 PM

Converting a byte array to an image in WinRT

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)