File Save Picker - Save Edited Image (C# Metro app

2019-07-16 18:02发布

问题:

I want to open an image, edit it, and then save it. I am able to open a file, but I have problems saving it. The way I have written the code, I can only save a file with .jpg but there is nothing in it.

Please explain to me how to save the image I have opened and edited(not made yet).

public sealed partial class MainPage : Page
{
    BitmapImage originalImage = new BitmapImage();

    public MainPage()
    {
        this.InitializeComponent();
    }

    private async void OpenButton_Click(object sender, RoutedEventArgs e)
    {
        var filePicker = new FileOpenPicker();
        filePicker.FileTypeFilter.Add(".jpg");
        filePicker.FileTypeFilter.Add(".jpeg");
        filePicker.FileTypeFilter.Add(".gif");
        filePicker.ViewMode = PickerViewMode.Thumbnail;
        filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        filePicker.SettingsIdentifier = "PicturePicker";
        filePicker.CommitButtonText = "Select File";
        StorageFile selectedFile = await filePicker.PickSingleFileAsync();
        var stream = await selectedFile.OpenAsync(FileAccessMode.Read);

        if (selectedFile != null)
        {
            originalImage.SetSource(stream);
            pictureBox.Source = originalImage;
        }
    }

    private async void SaveButton_Click(object sender, RoutedEventArgs e)
    {
        FileSavePicker savePicker = new FileSavePicker(); 
        savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
        savePicker.FileTypeChoices.Add("jpeg image", new List<string>() { ".jpg" });
        savePicker.SuggestedFileName = "EditedImage";
        StorageFile file = await savePicker.PickSaveFileAsync();
    }
}

回答1:

After creating an Images file you need to Update it see FileSavePicker class.

Add the following code in your SaveButton_Click method and try modify it.

This will let you update your created file into real image file.

if (file != null)
{
    // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
    CachedFileManager.DeferUpdates(file);
    // write to file
    await FileIO.WriteTextAsync(file, file.Name);
    // Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
    // Completing updates may require Windows to ask for user input.
    FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
    if (status == FileUpdateStatus.Complete)
    {
        OutputTextBlock.Text = "File " + file.Name + " was saved.";
    }
    else
    {
        OutputTextBlock.Text = "File " + file.Name + " couldn't be saved.";
    }
}
else
{
    OutputTextBlock.Text = "Operation cancelled.";
}