将图像设置为图像源时覆盖(重新保存)图像的问题

4im*_*ble 12 c# wpf image save

美好的一天,

我在使用图像权限时遇到了一些麻烦.

我正在从文件加载图像,调整大小,然后将其保存到另一个文件夹.然后我就这样显示:

    uriSource = new Uri(Combine(imagesDirectoryTemp, generatedFileName), UriKind.Absolute);

    imgAsset.Source = new BitmapImage(uriSource);
Run Code Online (Sandbox Code Playgroud)

这工作正常,如果用户然后立即选择另一个图像并尝试将其保存在原始文件上,则会出现问题.

保存图像时会生成异常 "ExternalException: A generic error occurred in GDI+."

在一些游戏后,我已经将错误缩小到imgAsset.Source = new BitmapImage(uriSource);删除此行并且不设置imagesource将允许我多次覆盖此文件.

我还尝试将源设置为其他内容,然后重新保存,希望旧的引用将被处理,情况并非如此.

我怎么能通过这个错误?

谢谢,Kohan

编辑

现在使用此代码我没有得到异常,但图像源没有更新.此外,因为我没有使用SourceStream,我不知道我需要处理什么才能使这个工作.

       uriSource = new Uri(Combine(imagesDirectoryTemp, generatedFileName), UriKind.Absolute);

       imgTemp = new BitmapImage();
       imgTemp.BeginInit();
       imgTemp.CacheOption = BitmapCacheOption.OnLoad;
       imgTemp.UriSource = uriSource;
       imgTemp.EndInit();

       imgAsset.Source = imgTemp;
Run Code Online (Sandbox Code Playgroud)

Ray*_*rns 39

你快到了.

  • 使用BitmapCacheOption.OnLoad是防止文件被锁定的最佳解决方案.

  • 每次还需要添加BitmapCreateOptions.IgnoreImageCache时,要使其重新读取文件.

在代码中添加一行应该这样做:

  imgTemp.CreateOption = BitmapCreateOptions.IgnoreImageCache;
Run Code Online (Sandbox Code Playgroud)

从而导致此代码:

  uriSource = new Uri(Combine(imagesDirectoryTemp, generatedFileName), UriKind.Absolute);
  imgTemp = new BitmapImage();
  imgTemp.BeginInit();
  imgTemp.CacheOption = BitmapCacheOption.OnLoad;
  imgTemp.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
  imgTemp.UriSource = uriSource;
  imgTemp.EndInit();
  imgAsset.Source = imgTemp;
Run Code Online (Sandbox Code Playgroud)