这是我的代码
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(),谁可以帮助我?
答案 0 :(得分:5)
在UWP中,您可以使用HttpContent.ReadAsStreamAsync
方法获取Stream
,然后将Stream
转换为IRandomAccessStream
,以便在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 (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;
}
}
}
此外,BitmapImage
具有UriSource
属性,您只需使用此属性即可获取在线图片。
bitmap.UriSource = new Uri(txtUri.Text);