2016-08-05 80 views
1

我試圖在我的WPF應用程序中加載大約20張圖像。只有第一張圖片完全加載。其他圖像部分加載。當我用斷點來調試我試圖加載每個圖像後2秒,並運行良好。圖像部分加載

代碼

圖像將被加載等,

foreach (string path in ImagesCollection) 
    { 
     DisplayImage = LoadImage(path); 
    } 

負載圖像的方法,

MemoryStream mem; 

if (!string.IsNullOrEmpty(path) && (File.Exists(path))) 
    { 

     FileInfo ImageFile = new FileInfo(path); 
     ImageFile.Refresh(); 
     if (mem != null) 
      { 
       mem.Dispose(); 
      } 
     using (var stream = ImageFile.OpenRead()) 
      { 
       mem = new MemoryStream(); 

       stream.CopyTo(mem); 

      } 
     mem.Position = 0; 
     ImageFrame = BitmapFrame.Create(mem); 

    } 

截圖:

enter image description here

我相信Dispose或新的實例使圖像無法加載。請幫助。

+1

有你爲什麼不使用'BitmapFrame.Create(新的URI(路徑))任何理由'沒有所有的數據流複製? – Clemens

+0

@Clemens不,圖像被加載到多個位置,並且MS Paint中還有一個編輯和保存功能。使用'新的Uri(路徑)'拋出'訪問衝突錯誤'?不確定。 – iamCR

+0

@HenkHolterman你可以請改革嗎? – iamCR

回答

1

BitmapFrame.Create狀態的文檔

這意味着你的「bitmapStream只能當的OnLoad緩存選項用於創建框架後關閉。直到需要的框架默認的OnDemand緩存選項保留流」一旦將它傳遞給BitmapFrame,就不能重新使用MemoryStream。這是錯誤的來源。

效率只是通過FileStream。 加載圖像方法

if (!string.IsNullOrEmpty(path) && (File.Exists(path))) 
{ 

    var stream = ImageFile.OpenRead()) 
    ImageFrame = BitmapFrame.Create(stream); 
} 
+0

當我嘗試加載大小> 5Mb的圖像文件時,經常會造成內存異常。 – iamCR

+0

然後我建議你將圖像的FileStream傳遞給BitmapFrame.Create。通過將它讀入MemoryStream中,您正在創建不必要的內存壓力。 ImageFrame會爲您緩存性能。 – PhillipH

+0

你可以請重構和發佈代碼? – iamCR