Thomas KiTe Trentin
Thomas KiTe Trentin

Reputation: 600

Displaying a picture stored in Storage file in a metroapp

I would like to display the content of a picture stored in a StorageFile through a binding, but whatever I'm trying to do it doesn't seem to work.

Here are the two solutions I have already tested :

string img =( await CompetencesFolder.GetFileAsync(FormatImageNameToFileName(imageName))).Path;

And then returning the path obtained (a full absolute path to the file) to the source Property through 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 binded property.

None of these methods works ..

Do anyone have an idea?

EDIT : FIX

Here is 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 did a mix of the 2 samples above : I created my bitmapImage from the absolute URI of the picture (LOCAL_REPOSITORY contains a reference to the local storage : ApplicationData.Current.LocalFolder)

I still can't figure why the 2 other ways failed : I usually bind my image directly to an Uri, a string or a BitmapImage, and it works ..

Upvotes: 4

Views: 12447

Answers (1)

Zhiming Xue
Zhiming Xue

Reputation: 352

The code below shows how you can use the loadimage method in an app: create a blank app, add an Image and a Button to the main 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;

    }

Upvotes: 10

Related Questions