问题
this is my code
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;
}
}
}
but now I can't use WriteToStreamAsync() in uwp, who can help me?
回答1:
In UWP you can use HttpContent.ReadAsStreamAsync
method to get the Stream
and then convert the Stream
to IRandomAccessStream
to use it in BitmapImage
. You can try like following:
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;
}
}
}
Besides, BitmapImage
has a UriSource
property, you can just use this property to get online image.
bitmap.UriSource = new Uri(txtUri.Text);
来源:https://stackoverflow.com/questions/33538215/how-to-convert-a-stream-to-bitmapimage