在 Metro 风格应用中将图像下载到本地存储

Download an image to local storage in Metro style apps(在 Metro 风格应用中将图像下载到本地存储)
本文介绍了在 Metro 风格应用中将图像下载到本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

接下来我该怎么做才能将下载的图像存储为 localfile.jpg?

What do I do next to store downloadedimage as localfile.jpg?

推荐答案

看起来像下面来自 Windows 8 的 HttpClient 示例的代码解决了这个问题

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 风格应用中将图像下载到本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)