2015-11-05 51 views
0

這是我的代碼如何將流轉換爲BitmapImage的

private async void OnGetImage(object sender, RoutedEventArgs e) 
     { 
      using (HttpClient client = new HttpClient()) 
      { 
       try 
       { 
        HttpResponseMessage response = await client.GetAsync(new Uri(txtUri.Text)); 

        BitmapImage bitmap = new BitmapImage(); 

        if (response != null && response.StatusCode == HttpStatusCode.OK) 
        { 

         using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) 
         { 
          await response.Content.WriteToStreamAsync(stream); 
          stream.Seek(0UL); 
          bitmap.SetSource(stream); 
         } 
         this.img.Source = bitmap; 
        } 
       } 
       catch (Exception) 
       { 

        throw; 
       } 
      } 
     } 

,但現在我不能在UWP使用WriteToStreamAsync(),誰可以幫幫我嗎?

回答

5

在UWP你可以使用HttpContent.ReadAsStreamAsync方法來獲得Stream然後轉換StreamIRandomAccessStreamBitmapImage使用它。你可以嘗試像以下:

private async void OnGetImage(object sender, RoutedEventArgs e) 
{ 
    using (HttpClient client = new HttpClient()) 
    { 
     try 
     { 
      HttpResponseMessage response = await client.GetAsync(new Uri(txtUri.Text)); 

      BitmapImage bitmap = new BitmapImage(); 

      if (response != null && response.StatusCode == HttpStatusCode.OK) 
      { 
       using (var stream = await response.Content.ReadAsStreamAsync()) 
       { 
        using (var memStream = new MemoryStream()) 
        { 
         await stream.CopyToAsync(memStream); 
         memStream.Position = 0; 

         bitmap.SetSource(memStream.AsRandomAccessStream()); 
        } 
       } 
       this.img.Source = bitmap; 
      } 
     } 
     catch (Exception) 
     { 
      throw; 
     } 
    } 
} 

此外,BitmapImageUriSource屬性,你可以使用這個屬性來獲取在線圖片。

bitmap.UriSource = new Uri(txtUri.Text); 
+0

你很聰明,它的工作原理 –

相關問題