C# 正确处理内存流(WPF图像转换)
有人能告诉我如何最好地处理内存流吗?以前,我有这个,一切都很好:C# 正确处理内存流(WPF图像转换),c#,.net,wpf,image,C#,.net,Wpf,Image,有人能告诉我如何最好地处理内存流吗?以前,我有这个,一切都很好: MemoryStream strmImg = new MemoryStream(profileImage.Image); BitmapImage myBitmapImage = new BitmapImage(); myBitmapImage.BeginInit(); myBitmapImage.StreamSource = strmImg; myBitmapImage.DecodePixelWidth = 200; myBitm
MemoryStream strmImg = new MemoryStream(profileImage.Image);
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.StreamSource = strmImg;
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.DecodePixelWidth = 250;
myBitmapImage.EndInit();
this.DemographicInformation.EmployeeProfileImage = myBitmapImage;
后来我意识到,由于MemoryStream
实现了IDisposable
,我将有一个内存泄漏,应该在我使用它之后进行处理,这导致我实现了以下功能:
using(MemoryStream strmImg = new MemoryStream(profileImage.Image))
{
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.StreamSource = strmImg;
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.DecodePixelWidth = 250;
myBitmapImage.EndInit();
this.DemographicInformation.EmployeeProfileImage = myBitmapImage;
}
问题出在这一行代码中:
myBitmapImage.StreamSource = strmImg;
我的假设是这是引用内存位置,dispose显然会清理该位置,它在过去工作过,因为它从未被正确地处理过
我的问题是,如何使用
MemoryStream
并在使用后正确处理它,同时仍然保留我需要的转换数据(图像
)?您需要添加这一行:
myBitmapImage.CacheOption = BitmapCacheOption.OnLoad;
在加载时将整个图像缓存到内存中。如果没有此行,CacheOption
属性的默认值是OnDemand
,它保留对流的访问,直到需要图像为止。因此,您的代码应该是:
using(MemoryStream strmImg = new MemoryStream(profileImage.Image))
{
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.CacheOption = BitmapCacheOption.OnLoad;
myBitmapImage.StreamSource = strmImg;
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.DecodePixelWidth = 250;
myBitmapImage.EndInit();
this.DemographicInformation.EmployeeProfileImage = myBitmapImage;
}
真是太棒了。非常感谢。请注意,处理MemoryStream是一种很好的做法(仅仅因为它是一次性的),但如果不这样做,它实际上不会泄漏。特别是,Dispose实际上并没有释放内存;只有当GC收集MemoryStream时,才会发生这种情况。由于BitmapImage保留对MemoryStream的引用,因此在收集BitmapImage之前无法收集它。