Search code examples
uwpwindows-10-mobile

Save image picked with FileOpenPicker


I want to create an app where the user can select multiple images from its local photo storage and I want to load this photos into the app. The user must be able to find them every time he open the app. I used the FileOpenPicker to let the user selecting the photos with the PickMultipleFilesAsync() method. Now I don't know how can I save the photos to show them to the user next time he opens the app.

This is my code:

private async void AddButton_Click(object sender, RoutedEventArgs e)
{
    FileOpenPicker openPicker = new FileOpenPicker();
    openPicker.ViewMode = PickerViewMode.Thumbnail;
    openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
    openPicker.FileTypeFilter.Add(".jpg");
    openPicker.FileTypeFilter.Add(".jpeg");
    openPicker.FileTypeFilter.Add(".bmp");
    openPicker.FileTypeFilter.Add(".png");
    IReadOnlyList<StorageFile> files = await openPicker.PickMultipleFilesAsync();
    if (files.Count > 0)
    {
        foreach (StorageFile file in files)
        {
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.DecodePixelHeight = 332;
            bitmapImage.DecodePixelWidth = 200;
            IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
            await bitmapImage.SetSourceAsync(stream);
            Wallpapers.Add(bitmapImage);
            stream.Dispose();
        }
    }
}

Thanks all.


Solution

  • If I understand your question correctly, you want to remember the location of where the photos were saved (or photos were copied from -- doesn't really matter). You have to make use of the Settings service.

    You can save info like file path using the Windows.Storage.ApplicationData.Current.LocalSettings.Values settings dictionary for later recall.

    For example: Windows.Storage.ApplicationData.Current.LocalSettings.Values["PhotosPath"] = file.Path;

    where file is StorageFile object as shown in your code, and next time you retrieve Windows.Storage.ApplicationData.Current.LocalSettings.Values["PhotosPath"] to initialize your file object with the Path.

    You can shorten the above code line by instead declaring using Windows.Storage; namespace (which I think you already did for StorageFile) and just use ApplicationData.Current.LocalSettings.Values["PhotosPath"] part in your code.

    Further advice: If you're using T10 Template in your project, you wouldn't want to use Windows.Storage.ApplicationData.Current.LocalSettings.Values for settings directly. T10 has a more comprehensive settings service built upon Windows.Storage.ApplicationData.Current in the Minimal Template (as opposed to the alternative Blank Template) and that's what you'd want to use instead.