gpt4 book ai didi

c# - 当我尝试使用图像源时出现 ObjectDisposedException

转载 作者:行者123 更新时间:2023-11-30 16:15:20 25 4
gpt4 key购买 nike

我需要在我的面板中添加一个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);
// ...
}

发生这种情况是因为我关闭了源代码,但如果我不关闭它,我将无法再次加载同一文件。

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

最佳答案

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

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;

关于c# - 当我尝试使用图像源时出现 ObjectDisposedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19755143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com