Sep 3 2011

Displaying an Image from Isolated Storage

Category: MobileJoel Ivory Johnson @ 04:51

I was writing some code for someone and for the scenario I needed to display images that were stored in isolated storage. Unfortunately at present the Image element in Silverlight doesn't support displaying images from Isolated storage. You must load the image yourself and then give the loaded image to an Image element. At first glance this is annoying because I wanted to just give the image a URI to something stored in solated storage and let the element do it's magic. After a few minutes of thinking I realized I can still do this provided I create a converter to do some of the needed work.  I wanted to ensure the converter was both compatible with the URIs that point to isolated storage and those that refer to locations on the internet. 

public class FilePathToImageConverter: IValueConverter
{
    private static IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string path = value as string;
        if (String.IsNullOrEmpty(path))
            return null;
        if((path.Length>9)&&(path.ToLower().Substring(0,9).Equals("isostore:")))
        {
            using (var sourceFile = ISF.OpenFile(path.Substring(9), FileMode.Open, FileAccess.Read))
            {
                BitmapImage bm = new BitmapImage();
                bm.SetSource(sourceFile);
                return bm;
            }
        }
        else
        {
            BitmapImage bm = new BitmapImage(new Uri(path));
            return bm;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

To use it bind a string value to the Source property of the Image element. The file path must be prefixed with "isostore:" for the converter to extract the image from isoated storage. if the "isostore:" prefix is not present the converter will attempt to load the image using a regular Uri.

Tags: ,