2013-09-05 61 views
2

我是從一個網站異步下載圖像的。我想將圖像列表保存到IsolatedStorage中。流不可序列化,所以我必須將其轉換爲字節數組。但是它不讀取Stream中while循環中的ReadFully()方法。在Windows Phone中異步下載之後將流轉換爲字節數組

這裏是我正在嘗試下載圖片:

HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest; 
    request.Headers["Referer"] = "http://www.website.com"; 
    request.BeginGetResponse((result) => 
    { 
     Stream imageStream = request.EndGetResponse(result).GetResponseStream(); 
     Deployment.Current.Dispatcher.BeginInvoke(() => 
     { 
      // Set stream as the source of image 
      BitmapImage bitmapImage = new BitmapImage(); 
      bitmapImage.CreateOptions = BitmapCreateOptions.BackgroundCreation; 
      bitmapImage.SetSource(imageStream); 
      image.Source = bitmapImage; 

      // Convert stream to byte array and save in the custom list with the uri of the image 
      ls.Add(new DownloadedImages() { Image = ReadFully(imageStream), URI = uri }); 
      ds.SaveMyData(ls, "BSCImages"); 
     }); 
    }, null); 

這裏是轉換流字節數組的方法:

public static byte[] ReadFully(Stream input) 
     { 
      byte[] buffer = new byte[input.Length]; 
      using (MemoryStream ms = new MemoryStream()) 
      { 
       int read; 
       while ((read = input.Read(buffer, 0, buffer.Length)) > 0) 
       { 
        ms.Write(buffer, 0, read); 
       } 
       return ms.ToArray(); 
      } 
     } 

更新

這是沒有進入while循環。所以字節數組總是空的。 enter image description here

+0

問題是什麼?你什麼意思是不讀流?有什麼異常嗎?流長度是否爲0? –

+0

@LeoLorenzoLuis我已經更新了問題 –

回答

3

,因爲你在傳遞給ReadFully之前創建bitmapImage消費流imageStream

首先得到byte[],然後用它來形成圖像,並傳送到new DownloadedImages()

+2

謝謝。我知道了。我糾正了代碼,它現在可以工作。 –

相關問題