【问题标题】:ObjectDisposedException when I try to use an Image source当我尝试使用图像源时出现 ObjectDisposedException
【发布时间】:2013-11-14 07:53:57
【问题描述】:

我需要在我的面板中添加一个Image,所以我使用以下代码:

var image = new Image();
var source = new BitmapImage();
source.BeginInit();
source.CacheOption = BitmapCacheOption.OnLoad;
source.StreamSource = new FileStream(filename, FileMode.Open);
source.EndInit();

// I close the StreamSource so I can load again the same file
source.StreamSource.Close();
image.Source = source;

问题是当我尝试使用我的图像源时,我得到一个ObjectDisposedException

var source = ((BitmapImage)image.Source).StreamSource;

// When I use source I get the exception
using (var stream = new MemoryStream((int)(source.Length)))
{
    source.Position = 0;
    source.CopyTo(stream);
    // ...
}

这是因为我关闭了源,但如果我不关闭它,我将无法再次加载同一个文件。

我该如何解决这个问题(即关闭源以便能够多次加载同一个文件,并且能够在不出现异常的情况下使用源)?

【问题讨论】:

  • 为什么不直接传Uri源,让组件处理呢? msdn.microsoft.com/en-us/library/aa970269(v=vs.110).aspx
  • @SebastianPiu 我无法使用 UriSource,因为当我检索 StreamSource 时它为空。
  • 你不应该释放图像的流。只要您正在显示图像,就保持打开状态
  • @Nick UriSource 是 StreamSource 的替代品。如果你使用一个,你不应该接触另一个。如果可能的话,我会推荐使用 UriSource,在这种情况下你不需要处理任何东西。

标签: c# wpf image exception stream


【解决方案1】:

以下解决方案应该适合您:

var image = new Image();
var source = new BitmapImage();
source.BeginInit();
source.CacheOption = BitmapCacheOption.OnLoad;

// Create a new stream without disposing it!
source.StreamSource = new MemoryStream();

using (var filestream = new FileStream(filename, FileMode.Open))
{
   // Copy the file stream and set the position to 0
   // or you will get a FileFormatException
   filestream.CopyTo(source.StreamSource);
   source.StreamSource.Position = 0;
}

source.EndInit();
image.Source = source;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 2020-09-28
    相关资源
    最近更新 更多