在 Metro 风格应用中将图像下载到本地存储 [英] Download an image to local storage in Metro style apps

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆