如何将流转换为BitmapImage

本文关键字:BitmapImage 转换 | 更新日期: 2023-09-27 18:20:34

这是我的代码

 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(),谁能帮我?

如何将流转换为BitmapImage

在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);