2

我想打开一张图片,编辑它,然后保存它。我可以打开一个文件,但我无法保存它。我编写代码的方式,我只能用 .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();
    }
}
4

1 回答 1

1

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

在您的方法中添加以下代码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.";
}
于 2014-11-21T00:06:05.947 回答