谁能告诉我如何最好地处理内存流?以前,我有这个并且一切正常:
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;
我的假设是这是在引用内存位置,并且处置显然会清理该位置,并且它在过去有效,因为它从未被正确处置。
我的问题是,如何使用 MemoryStream
并在使用后妥善处理它,同时仍保留我需要的转换数据(Image
)?
最佳答案
你需要添加这一行:
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;
}
关于c# - 正确处理内存流(WPF 图像转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33532680/