Search code examples
c#imageuwppathfileopenpicker

How to display an image chosen by a file open picker in UWP C#?


I implemented a File Open Picker into a Universal Windows Platform Application for choosing an image to display in a list item.

However, after getting the image path from the file open picker, the path can't be set as an image source neither as a URI nor network path (tried "file:///" + path).

Is there a way to show an image from a file open picker selected path?

If not, is there any way to open a local image from the computer in the app?


Solution

  • I implemented a File Open Picker into a Universal Windows Platform Application for choosing an image to display in a list item.

    UWP does not support file:// uri scheme, if you open the file with file open picker, you could open the file as stream, and convert it to BitmapImage like the following.

    try
    {
        var picker = new Windows.Storage.Pickers.FileOpenPicker
        {
            ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail,
            SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary
        };
        picker.FileTypeFilter.Add(".jpg");
        picker.FileTypeFilter.Add(".jpeg");
        picker.FileTypeFilter.Add(".png");
    
        Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
        if (file != null)
        {
            using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                BitmapImage bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(fileStream);
                MyImage.Source = bitmapImage;
    
            }
        }
       
    }
    catch (Exception ex)
    {
    
        throw ex;
    }