簡體   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