C# 将图像设置为图像源时覆盖(重新保存)图像时出现问题

C# 将图像设置为图像源时覆盖(重新保存)图像时出现问题,c#,wpf,image,save,C#,Wpf,Image,Save,大家好 我在图像权限方面遇到了一些问题 我正在从文件中加载图像,调整其大小,然后将其保存到另一个文件夹中。 然后我这样展示: uriSource = new Uri(Combine(imagesDirectoryTemp, generatedFileName), UriKind.Absolute); imgAsset.Source = new BitmapImage(uriSource); 这工作正常,如果用户随后立即选择另一个图像并试图将其保存在原始文件上,则会出现问题 保

大家好

我在图像权限方面遇到了一些问题

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

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

    imgAsset.Source = new BitmapImage(uriSource);
这工作正常,如果用户随后立即选择另一个图像并试图将其保存在原始文件上,则会出现问题

保存我的图像时会生成异常
“ExternalException:GDI+中发生一般错误”。

经过一番尝试后,我将错误缩小到
imgAsset.Source=new-BitmapImage(uriSource)因为删除此行而不设置imagesource将允许我多次覆盖此文件

在重新保存之前,我还尝试将源代码设置为其他内容,希望旧的引用能够被处理,但事实并非如此

我怎样才能克服这个错误

谢谢, 科汉

编辑

现在使用这段代码我没有得到异常,但是图像源没有更新。另外,由于我没有使用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;

听起来很像我开发的问题,WPF不会处理图像,因此锁定了文件。查看我为解决此问题而写的文章。

当您在任何WPF控件中加载图像时,让我们处理您的图像,直到您关闭应用程序才释放它。原因是。。。我不知道确切的情况,可能是在幕后传递一些DirectX代码,这些代码永远不知道WPF应用程序何时发布图像。。 使用此代码加载图像

        MemoryStream mstream = new MemoryStream();
        System.Drawing.Bitmap bitmap = new Bitmap(imgName);
        bitmap.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg);
        bitmap.Dispose(); // Releases the file.

        mstream.Position = 0;

        image.BeginInit();
        image.StreamSource = mstream;
        image.EndInit();
        this.img.Source = image ;   
这对我很有效。

你就快到了

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

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

在代码中添加一行应该可以:

  imgTemp.CreateOption = BitmapCreateOptions.IgnoreImageCache;
因此,导致该代码:

  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;

您好,谢谢,我不再生成错误,但在更新后,图像源没有更新。我是否需要按照您的示例处理某些内容,还是需要以某种方式刷新imagesource?谢谢。这可以工作,但比使用BitmapCacheOptions.OnLoad和BitmapCreateOptions.IgnoreImageCache效率低很多,因为:1。它将数据的两个副本保存在RAM 2中。速度较慢,因为在System.Drawing.Bitmap.Save调用期间有大量的解析和处理。如果imgName是仅由WPF处理的URI,则它也将不起作用。imgTemp.CreateOption应该是imgTemp.CreateOptions