Displaying an image stored in a repository file in metroapp
I would like to display the content of an image stored in a StorageFile via a binding, but everything I am trying to do does not seem to work.
Here are two solutions I've already tested:
string img =( await CompetencesFolder.GetFileAsync(FormatImageNameToFileName(imageName))).Path;
And then return the resulting path (full absolute file path) to the original property via a binding and:
BitmapImage img = await LoadImage(await CompetencesFolder.GetFileAsync(FormatImageNameToFileName(imageName)));
private static async Task<BitmapImage> LoadImage(StorageFile file)
{
BitmapImage bitmapImage = new BitmapImage();
FileRandomAccessStream stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.Read);
bitmapImage.SetSource(stream);
return bitmapImage;
}
Returning the final bitmapImage later to my bound property.
None of these methods work.
Anyone have an idea?
EDIT: FIX
Here's the code that solved the problem:
BitmapImage img = new BitmapImage() { UriSource = new Uri( LOCAL_REPOSITORY.Path + "/Assets/gfx/cards/" + FormatImageNameToFileName(imageName) + ".jpg", UriKind.RelativeOrAbsolute) };
I made a mixture of the two samples above: I created my bitmapImeydzh from absolute URI image (LOCAL_REPOSITORY contains a reference to the local store: ApplicationData.Current.LocalFolder
)
I still can't figure out why the 2 other ways failed: I usually bind my image directly to a Uri, String or BitmapImage and it works.
source to share
The code below shows how you can use the loadimage method in an application: create an empty application, add an image and a button to the home page.
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
// load file from document library. Note: select document library in capabilities and declare .png file type
string filename = "Logo.png";
Windows.Storage.StorageFile sampleFile = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync(filename);
// load file from a local folder
//Windows.Storage.StorageFile sampleFile = sampleFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("Assets\\Logo.png");
BitmapImage img = new BitmapImage();
img = await LoadImage(sampleFile);
myImage.Source = img;
}
private static async Task<BitmapImage> LoadImage(StorageFile file)
{
BitmapImage bitmapImage = new BitmapImage();
FileRandomAccessStream stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.Read);
bitmapImage.SetSource(stream);
return bitmapImage;
}
source to share