文件保存选择器 - 保存已编辑的图像(C#Metro应用程序)

时间:2014-11-20 23:48:38

标签: c# microsoft-metro filesavepicker

我想打开图像,编辑它,然后保存它。我能够打开一个文件,但是我在保存它时遇到了问题。我编写代码的方式,我只能保存一个带.jpg的文件,但其中没有任何内容。

请向我解释如何保存我已打开和编辑过的图像(尚未制作)。

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 个答案:

答案 0 :(得分:0)

创建图像文件后,您需要更新它,请参阅FileSavePicker class。

SaveButton_Click方法中添加以下代码,然后尝试修改它。

这样您就可以将创建的文件更新为真实图像文件。

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.";
}