正确处理内存流(WPF图像转换)

时间:2015-11-04 21:48:10

标签: c# wpf image type-conversion

谁能告诉我如何最好地处理内存流?以前,我有这个,一切正常:

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并在使用后正确处理,同时仍保留我需要的转换数据(图像)?

谢谢,

ROKA

1 个答案:

答案 0 :(得分:6)

您需要添加以下行:

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;
}