A file picker represents a UI element that lets the user choose and open files.
Step 1: Open a blank app and add a Button and a Image control either from the toolbox or by copying the following XAML code into your grid.
- <StackPanel Margin="10,40,0,0">
- <TextBlock Text="File Picker" FontSize="20"></TextBlock>
- <Button Name="imageOpenButton" Content="Open Image" Height="40" Width="120" Click="imageOpenButton_Click"></Button>
- <Image Margin="0,20,0,0" Name="selectedImage" Height="300" Width="300"></Image>
- </StackPanel>
Step 2 : Add the following namespaces to your project which is needed in further C# code:
- using Windows.Storage;
- using Windows.Storage.Pickers;
- using Windows.Storage.Streams;
- using Windows.UI.Xaml.Media.Imaging;
Step 3: Copy and paste the following code to the cs page which will be called on button clicking event and will start the file picker
and the selected image will be displayed.
- FileOpenPicker openPicker = new FileOpenPicker();
- openPicker.ViewMode = PickerViewMode.Thumbnail;
- openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
- openPicker.FileTypeFilter.Add(".jpg");
- openPicker.FileTypeFilter.Add(".jpeg");
- openPicker.FileTypeFilter.Add(".png");
- StorageFile image = await openPicker.PickSingleFileAsync();
- BitmapImage bitmapImage = new BitmapImage();
- using(IRandomAccessStream fileStream = await image.OpenAsync(FileAccessMode.Read))
- {
- bitmapImage.SetSource(fileStream);
- }
- selectedImage.Source = bitmapImage;
Step 4: Run your application and test yourself.