下载一个图像到Metro风格应用程序的本地存储 [英] Download an image to local storage in Metro style apps
问题描述
在的WinRT / C#中,我怎样的图像下载到本地文件夹,支持在线目录脱机使用的缓存?有没有办法直接下载图像和链接控制从缓存中作为备用让他们?
In WinRT / C#, How do I download an image to a local folder to support caching of an online catalogue for offline use? is there a way to directly download the images and link the control to get them from the cache as a fallback?
var downloadedimage = await HttpWebRequest.Create(url).GetResponseAsync();
StorageFile imgfile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"localfile.png", CreationCollisionOption.FailIfExists);
我该怎么办旁边downloadedimage存储为localfile.jpg?
What do I do next to store downloadedimage as localfile.jpg?
推荐答案
看起来像是从HttpClient的样本下面的代码为Windows 8解决问题。
Looks like the code below from the HttpClient sample for Windows 8 solves the issue
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Get, resourceAddress);
HttpResponseMessage response = await rootPage.httpClient.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead);
HttpClient的是一个HttpClient和其BaseAddress需要设置你的资源的服务器文件夹。那么我们可以做到这一点将其转换成图像源(如果那是我们正在下载的)
httpClient is a HttpClient, and its BaseAddress needs to be set a the server folder of your resource. we can then do this to convert that to an image source (if that's what we're downloading)
InMemoryRandomAccessStream randomAccessStream =
new InMemoryRandomAccessStream();
DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();
BitmapImage image = new BitmapImage();
imagecontrol.SetSource(randomAccessStream);
或此写入到文件
var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
filename, CreationCollisionOption.ReplaceExisting);
var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));
writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();
writer.DetachStream();
await fs.FlushAsync();
这篇关于下载一个图像到Metro风格应用程序的本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!