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