c# - 如何将流转换为 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 转换为 IRandomAccessStreamBitmapImage 中使用它。您可以尝试以下操作:

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

https://stackoverflow.com/questions/33538215/

相关文章:

windows - 使用 vmware 机器进行内核调试

c# - 在列表中查找一个属性包含重复值的对象

php - 检查字符串中是否存在多个单词之一?

azure - 单个 Azure Web App 的多个实例是否共享单个磁盘?

reactjs - 我如何在 react 中合并两个组件

sql - 基于两个表的select CASE语句

php - FILTER_SANITIZE_NUMBER_INT 不将字符串转换为 int

three.js - 是否可以在 Three.js 中使用带缓冲几何的三角形带?

python - 统一码编码错误 : 'ascii' codec can't encode char

bash - expr 显示表达式而不是求解它