我正在使用MVVM构建的Windows Phone 8.1 RT应用程序添加功能。我需要能够将图像下载到设备并保存/显示它。我已经可以使用固定网址中的图片执行此操作。
我们有一个随附的网站和API来与应用程序一起使用。它的工作方式是应用程序向API发送请求以获取相关图像的下载代码,然后将此代码连同文档的ID一起发送到网站,验证用户是否可以访问如果成功,应该提供文件。 API和网站已经与iOS和Android等效的应用程序一起使用,所以我知道它们有效。
要检索图像,我正在尝试使用HttpClient。这是我当前的代码,它从服务器获得响应,包含一些内容和图像的文件名(看起来是正确的):
Uri uri = new Uri("<website address>");
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("RequestToken", response.DownloadToken);
pairs.Add("DocumentID", "<doc ID>");
HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs);
HttpClient client = new HttpClient();
HttpResponseMessage response2 = await client.PostAsync(uri, formContent);
var imageContent = response2.Content.ReadAsInputStreamAsync();
我正在尝试将内容写入流,然后将其转换为BitmapImage对象,然后我可以将其保存到设备并显示给用户。这是我正在努力的转变。我的计划是将InputStream转换为bytearray,然后将其转换为Bitmap。问题是,我在8.1中找不到任何可以做到这一点的扩展方法,而且在文档帮助方面也很少。
有人能指出我在正确的方向吗?也许有更好的方法从HttpResponseMessage.Content转换为BitmapImage?
答案 0 :(得分:3)
确保您导入正确的 HttpClient :
using Windows.Web.Http;
并导入其他必要的命名空间:
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;
然后,正如您在qurestion中所写,获取 IInputStream ,但请务必使用 await 与 ReadAsInputStreamAsync():
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(uri, formContent);
// Do not forget to use an 'await'.
IInputStream imageStream = await response.Content.ReadAsInputStreamAsync();
然后,将 IInputStream 复制到 IRandomAccessStream 中:
InMemoryRandomAccessStream randomAccessStream =
new InMemoryRandomAccessStream();
await RandomAccessStream.CopyAsync(imageStream, randomAccessStream);
这很重要,快退 IRandomAccessStream :
// Rewind.
randomAccessStream.Seek(0);
最后,创建一个 BitmapImage 并将其分配给您的XAML Image 控件:
var bitmap = new BitmapImage();
bitmap.SetSource(randomAccessStream);
MyImage.Source = bitmap;
这就是全部!
如果您需要测试URI,请尝试以下方法:
Uri uri = new Uri("http://heyhttp.org/emoji.png");
HttpResponseMessage response = await client.GetAsync(uri);