簡體   English   中英

正確處理內存流(WPF圖像轉換)

[英]Disposing a memory stream properly (WPF Image 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

你需要添加這一行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM