2014-01-27 29 views
2

我使用緩存機制,它將圖像保存到隔離存儲並在下次加載時,尤其是在沒有Internet連接時。然而,它對於小圖像工作正常,但不適用於大約200kb的「大」圖像。將「大」數據流設置爲BitmapImage的源時出錯

這是我的代碼:

public static object ExtractFromLocalStorage(Uri imageFileUri, string imageStorageFolder) 
{ 
    var isolatedStoragePath = GetFileNameInIsolatedStorage(imageFileUri, imageStorageFolder); 

    MemoryStream dataStream; 
    using (var fileStream = Storage.OpenFile(isolatedStoragePath, FileMode.Open, FileAccess.Read)) 
    { 
     if (fileStream.Length > int.MaxValue) 
      return null; 
     dataStream = new MemoryStream((int)fileStream.Length); 
     var buffer = new byte[4096]; 
     while (dataStream.Length < fileStream.Length) 
     { 
      var readCount = fileStream.Read(buffer, 0, Math.Min(buffer.Length, (int)(fileStream.Length - dataStream.Length))); 
      if (readCount <= 0) 
      { 
       throw new NotSupportedException(); 
      } 
      dataStream.Write(buffer, 0, readCount); 
     } 
    } 
    var bi = new BitmapImage(); 
    Deployment.Current.Dispatcher.BeginInvoke(() => bi.SetSource(dataStream)); 
    return bi; 
} 

小圖片做工精細,但我得到以下異常時bi.SetSource被調用,加載此類200KB +圖像時: 組件無法找到。 (來自HRESULT的例外:0x88982F50)

有什麼我可以做的嗎? 200kb不是太大,文件保存良好,並存在本地。我希望有人能幫助我,因爲這是我的應用程序的最後一個塞...:/

EDIT(1月31日):

我又從頭開始,使用KawagoeToolkit庫,我延長了必要我的應用程序的方法。它運作良好,但我仍然想知道爲什麼上面給出了這樣一個奇怪的例外。

+0

圖像的尺寸是多少? –

+0

這是不同的,大多數都是大約800x600。它是來自Foursquare的全屏圖像(拇指等工作正常),例如這一個:https://irs2.4sqi.net/img/general/original/2DMDNSQXGMVWJBUSSTA4LRVIUVQKXUBONTEBJ5CKI5VJHFRM.jpg – sibbl

+0

它是WP7還是WP8?是否會爲特定圖像拋出異常,如果可以,您是否可以發佈該圖像?到目前爲止,我一直無法重現錯誤。 – lisp

回答

0

不必在不需要時使用調度程序。它將引入閉包語義。 在您的方法中,即使您處於另一個同步上下文中,也沒有任何意義。因爲涉及的GUI線程沒有任何東西。

無論如何,我已測試過您的代碼,但有一點不同 - 我使用StorageFile而不是IsolatedStorage。它完美的作品。

private async void Button_Click(object sender, RoutedEventArgs e) 
    { 
     //622Kb: http://www.nasa.gov/sites/default/files/styles/1920x1080_autoletterbox/public/pia17147.jpg?itok=6jErm40V 
     //2.7Mb: http://www.nasa.gov/sites/default/files/304_lunar_transit_14-00_ut_0.jpg 
     StorageFile imageFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\test3.jpg"); 
     MemoryStream mz; 
     using (var z = await imageFile.OpenStreamForReadAsync()) 
     { 
      if (z.Length > int.MaxValue) return; 
      mz = new MemoryStream((int)z.Length); 
      var buffer = new byte[4096]; 

      while (mz.Length < z.Length) 
      { 
       var readCount = z.Read(buffer, 0, Math.Min(buffer.Length, (int)(z.Length - mz.Length))); 
       if (readCount <= 0) 
       { 
        throw new NotSupportedException(); 
       } 
       mz.Write(buffer, 0, readCount); 
      }     
     } 

     var bmp = new BitmapImage(); 
     bmp.SetSource(mz); 
     //Deployment.Current.Dispatcher.BeginInvoke(() => img.Source = bmp); // if in another sync context only 
     img.Source = bmp; 
    } 
+0

是的,我也嘗試使用此方法加載大資產,但我緩存來自API的圖像不在應用程序的安裝位置。他們也不應該在那裏緩存,如果他們? – sibbl

相關問題