【发布时间】: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