如何将流转换为 BitmapImage [英] How to convert a stream to BitmapImage

查看:32
本文介绍了如何将流转换为 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(),谁能帮帮我?

but now I can't use WriteToStreamAsync() in uwp, who can help me?

推荐答案

在 UWP 中你可以使用 HttpContent.ReadAsStreamAsync 方法来获取 Stream 然后转换StreamIRandomAccessStream 以在 BitmapImage 中使用它.您可以尝试如下:

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;
        }
    }
}

另外,BitmapImage 有一个 UriSource 属性,你可以使用这个属性来获取在线图像.

Besides, BitmapImage has a UriSource property, you can just use this property to get online image.

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

这篇关于如何将流转换为 BitmapImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆