65.9K
CodeProject is changing. Read more.
Home

Browse Photo in Windows Phone 8.1

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (2 votes)

Aug 5, 2014

CPOL
viewsIcon

10740

This tip will show the new way to browse photos with Windows Phone 8.1

Introduction

While developing apps, we need to browse Picture to modify them or to add user's information. Here is the easy way to do it on Windows Phone 8.1.

Background

It is so easy to Browse Photo in Windows Phone 8.0, however Windows Phone 8.1 has included some big changes.

Using the Code

First of all, you must add the capability PictureLibrary in the manifest file.

Add the Action Click on Button to Browse Picture:

     private void PickImage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var openPicker = new FileOpenPicker
                  {
                      SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                      ViewMode = PickerViewMode.Thumbnail
                  };

                // Filter to include a sample subset of file types.
                openPicker.FileTypeFilter.Clear();
                openPicker.FileTypeFilter.Add(".bmp");
                openPicker.FileTypeFilter.Add(".png");
                openPicker.FileTypeFilter.Add(".jpeg");
                openPicker.FileTypeFilter.Add(".jpg");

                PickImage(openPicker);
            }
            catch (Exception)
            {
                               
            }
        }

We add the majority of extensions that we use (bmp, png, jpeg, jpg).

Then this code calls the function PickImage that transfers the Picker to file.

Add the following code:

   private async void PickImage(FileOpenPicker openPicker)
        {
            try
            {
                this.completionSource = new TaskCompletionSource<StorageFile>();

                openPicker.PickSingleFileAndContinue();

                StorageFile file = await this.completionSource.Task;

                if (file != null)
                {
                   img.Source = await MakeImage(file);
                }
        }

After that, we set the Source of the Image, but after the Call of the Function MakeImage that transfers File to BitmapImage.

Add the function MakeImage:

       TaskCompletionSource<StorageFile> completionSource;

       WriteableBitmap writimage;

       async Task<ImageSource> MakeImage(StorageFile file)
        {
            BitmapImage bitmapImage = null;

            if (file != null)
            {
                bitmapImage = new BitmapImage();

                using (var stream = await file.OpenReadAsync())
                {
                    await bitmapImage.SetSourceAsync(stream);
                }
            }
            return (bitmapImage);
        }

History

Browsing pictures is one of the famous keys to developing and building a useful app.