【问题标题】:Download Image UWP (C#)下载图像 UWP (C#)
【发布时间】:2016-04-14 15:12:35
【问题描述】:

我正在为 Windows 10 移动版编写应用程序。

我的 XAML 中有图像。

<Image x:Name="productimage" HorizontalAlignment="Left" Height="146" VerticalAlignment="Top" Width="135"/>

我需要从 URL 下载图片并放到 Image 中

我该怎么做?

感谢您的帮助。

【问题讨论】:

  • 这不是重复的,因为这些答案不能解决我的问题。这段代码中的任何一个都不起作用。我有 UWP 应用程序。 @EldarDordzhiev
  • 我引用的问题是您问题的确切解决方案。 UWP 和 Windows 8 XAML UI 是基本相同的 UI 框架,解决方案适用于两者。如果代码不起作用,请与我们分享您的努力。 Спасибо.

标签: c# win-universal-app


【解决方案1】:

你可以试试这个snipet

System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

...

System.Net.Http.HttpResponseMessage imageResponse = await client.GetAsync(imageUrl);

// A memory stream where write the image data
Windows.Storage.Streams.InMemoryRandomAccessStream randomAccess =
new Windows.Storage.Streams.InMemoryRandomAccessStream();

Windows.Storage.Streams.DataWriter writer = 
new Windows.Storage.Streams.DataWriter(randomAccess.GetOutputStreamAt(0));

// Write and save the data into the stream
writer.WriteBytes(await imageResponse.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();

// Create a Bitmap and assign it to the target Image control
Windows.UI.Xaml.Media.Imaging.BitmapImage bm =
new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await bm.SetSourceAsync(randomAccess);
productimage.Source = bm;

这不是我的片段,但也应该适用于 UWP。 UWP 与 Windows 8.1 非常相似。所以你可以尝试搜索WinRT示例

【讨论】:

  • 我需要在哪里输入网址?
  • imageUrl - 这是带有 URL 的字符串
  • 你有等待,但没有异步。
  • 您需要在方法或按钮点击事件中添加异步谓词
【解决方案2】:

我找到了问题的答案

很简单

string url = "url";
productimage.Source = new BitmapImage(new Uri(url, UriKind.Absolute));

感谢@Eldar Dordzhiev

【讨论】:

    【解决方案3】:

    此代码在 VB.Net 中。我想你可以阅读它并转换为 C#。我只是想帮忙。将 Windows.Web.Http 用于 UWP,因为 System.Net.Htpp 正在贬值。

    Imports Windows.Web.Http
    ...
    Dim client as New HttpClient
    Dim response = Await client.GetBufferAsync(ImgUri)
    stream = response.AsStream
    Dim mem = New MemoryStream()
    Await stream.CopyToAsync(mem)
    mem.Position = 0
    Dim img As New BitmapImage
    img.SetSource(mem.AsRandomAccessStream)
    Return img
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 2017-06-27
      • 1970-01-01
      • 2021-12-12
      相关资源
      最近更新 更多