简体   繁体   English

如何将流转换为BitmapImage

[英]How to convert a stream to BitmapImage

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? 但是现在我无法在uwp中使用WriteToStreamAsync(),谁可以帮助我?

In UWP you can use HttpContent.ReadAsStreamAsync method to get the Stream and then convert the Stream to IRandomAccessStream to use it in BitmapImage . 在UWP中,可以使用HttpContent.ReadAsStreamAsync方法获取Stream ,然后将Stream转换为IRandomAccessStream以在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. 此外, BitmapImage具有UriSource属性,您可以使用此属性获取在线图像。

bitmap.UriSource = new Uri(txtUri.Text);

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

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