Search code examples
c#windows-8windows-runtimefileopenpicker

Adding image outside of project C# Windows Store Application


In my xaml file I have an image named OutputImg. I also have a textblock named OutputTB for displaying the name of the image and a button which lets me choose an image from my Pictures folder.

Code behind :

private async void Button_Click_1(object sender, RoutedEventArgs e)
{
    FileOpenPicker openPicker = new FileOpenPicker();
    openPicker.ViewMode = Picker.ViewMode.List;
    openPicker.SuggestedStartLocation = PickerLocationId.PicutresLiibrary;
    openPicker.FileTypeFilter.Add(".png");
    StorageFile.file = await openPicker.PickSingleFileAsync();
    OutputTB.text = file.Name;


    BitmapImage image = new BitmapImage(new Uri(file.path));
    OutputImg.Source = image;
}

Question is that even though I dont get any errors, my picture won't show. It writes out the picture's name to OutputTB.text but Image just stays empty. How can I make my selected image appear in the OutputImg image box.

I understand that there might be a really basic thing I'm missing here but its just meant to be a learning project


Solution

  • You cannot use file.path to create the Uri object for the bitmap because file.path gives the old style path (e.g. c:\users\...\foo.png). The bitmap expects the new style uri path (e.g. ms-appdata:///local/path..to..file.../foo.png).

    However, as far as I know there isn't any way to specify the new style uri path for the Pictures Library. Therefore, you have to use a simple workaround:

    Since you have a reference to the file, you can instead get access to the file's stream, and then set the stream as the bitmap's source:

    StorageFile file = await openPicker.PickSingleFileAsync();
    OutputTB.text = file.Name;
    
    // Open a stream for the selected file.
    var fileStream =
        await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
    
    // Set the image source to the selected bitmap.
    BitmapImage image = new BitmapImage();
    image.SetSource(fileStream);
    
    OutputImg.Source = image;