Tuesday, 19 March 2013

Windows Store App Development Tutorial - Part 11 : FileOpenPicker

FileOpenPicker is an UI element, used to choose and open files. In order to use FileOpenPicker, we have to add "Windows.Storage.Pickers" namespace.

In this sample, I am taking a Button and Image control in the design page, whenever user clicks on Button, it opens FileOpenPicker to select an image from the collection of images which are from the local drive of computer. When the user selects a particular image, in binds that with Image control which is present in design page.

XAML Design of the page is as follows,

 <Image x:Name="image1" HorizontalAlignment="Left" Height="194" Margin="275,112,0,0" VerticalAlignment="Top" Width="200" Stretch="UniformToFill"/>
 <Button Content="Click" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Button_Click_1"/>


Following code is about how to use FileOpenPicker, write the code in button click event,

            FileOpenPicker picker = new FileOpenPicker();
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.ViewMode = PickerViewMode.Thumbnail;
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".png");
            var file = await picker.PickSingleFileAsync();
            var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

In the above code, 
  • Created an object of FileopenPicker,
  • Suggested start location
  • Assigned view mode as thumbnails
  • Added two file type filters are .jpg, .png
  • Reading complete stream of selected image
Now, we have to bind selected image to the image control which is in design page. For that we are using BitmapImage class. In order to use this class, add the "Windows.UI.Xaml.Media.Imaging" namespace.

            BitmapImage bmp = new BitmapImage();
            bmp.SetSource(stream);
            image1.Source = bmp;



In the above code, I am creating object of BitmapImage class,  setting the source to stream and setting image control source to selected image.

I hope this is useful. Thank You.

No comments:

Post a Comment