繁体   English   中英

如何将流转换为BitmapImage

[英]How to convert a stream to 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(),谁可以帮助我?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM