这是我的代码
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(),谁能帮帮我?
最佳答案
在 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);
https://stackoverflow.com/questions/33538215/