2013-11-03 26 views
3

我需要一个Image添加到我的面板,所以我用下面的代码:的ObjectDisposedException当我尝试使用图片来源

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); 
    // ... 
} 

这是因为我关闭了源,但如果我不关闭它,我能不能够再次加载相同的文件。

我该如何解决这个问题(即关闭源代码以便能够多次加载同一个文件,并且能够使用源代码而不会发生异常)?

+0

为什么不直接通过开放的来源,让组件处理呢? http://msdn.microsoft.com/en-us/library/aa970269(v=vs.110).aspx –

+0

@SebastianPiu我不能使用UriSource,因为当我检索StreamSource时它是空的。 – Nick

+0

您不应该丢弃图像流。只要你正在显示图像就保持打开状态 – Jehof

回答

3

如下解决方案为你工作:

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;