13

我使用以下代码显示来自网络服务器的图像:

   <Image Source="{Binding Url}" />

图像会自动下载,我假设还有一些基于 Url 的缓存。

我的问题是,当应用程序离线时,可能缓存的图像不会显示。

有没有办法改变缓存行为,以便在没有可用网络时也加载图像?指向有关缓存的文档的指针也将非常有帮助。

4

5 回答 5

25

BitmapImage默认情况下自动缓存远程图像。它最好与 结合使用CreateOptions="BackgroundCreation"以获得最佳性能。

<Image Height="100" Width="100" Margin="12,0,9,0">
  <Image.Source>
    <BitmapImage UriSource="{Binding ImgURL}" CreateOptions="BackgroundCreation"/>
  </Image.Source>
</Image>

这篇 MSDN 博客文章虽然旧但仍然相关,列出并解释了所有内容,CreationOptions并且在大多数模式下缓存是自动的。

我使用这些选项来显示许多带有图像的新闻项目,并且效果很好。我可以加载文章列表,退出应用程序并将飞行模式打开,然后启动应用程序的新实例,图像仍会加载。

手动方法

如果您想自己控制缓存并缓存 HTTPS 资源,那么很少有很好的例子......

于 2013-06-24T14:40:16.107 回答
5

我有一个解决方案给你。它是JetImageLoader,我为应用程序创建了它,我们需要在其中加载、缓存和显示大量徽标、图标等。

它可以用作绑定转换器,因此您甚至不应该更改您的代码!只需更新您的 XAML!

请查看存储库中的示例,您会喜欢的;)

特征:

  • 缓存在磁盘上
  • 缓存在内存中
  • 完全异步
  • 可用作绑定转换器或以编程方式从您的代码中使用
  • 完全开源,分叉和改进它!

这是示例:

<Image Source="{Binding ImageUrl, Converter={StaticResource MyAppJetImageLoaderConverter}}"/>
于 2013-10-12T22:36:49.480 回答
1

I don't think there is a build in way to do it, but you could save the images in IsolatedStorage and use a Converter that checks the internet availability and either returns the online or offline url.

A quick search yielded this which might be exactly what you are looking for (it's compatible to Windows Phone 7 and might not be the best solution for Windows Phone 8)

于 2013-06-23T14:15:37.493 回答
1

你也可以使用 FFImageLoading ( https://github.com/molinch/FFImageLoading/ )

特征

  • Xamarin.iOS(最低 iOS 7)、Xamarin.Android(最低 Android 4)、Xamarin.Forms 和 Windows(WinRT、UWP)支持
  • 可配置的磁盘和内存缓存
  • 类似下载/加载请求的重复数据删除
  • 错误和加载占位符支持
  • 图像可以自动下采样到指定大小(更少的内存使用)
  • WebP 支持
  • 图像加载淡入动画支持
  • 可以重试图片下载(RetryCount、RetryDelay)
  • 默认情况下禁用 Android 透明度(可配置)。节省 50% 的内存
  • 转换支持
    • 模糊变换
    • CircleTransformation、RoundedTransformation、CornersTransformation
    • 颜色空间变换、灰度变换、棕褐色变换
    • 翻转变换
    • 支持自定义转换(本机平台 ITransformation 实现)

这很简单:

<ff:MvxCachedImage Name="image"
    VerticalAlignment="Stretch" 
    HorizontalAlignment="Stretch"
    LoadingPlaceholder="loading.png"
    ErrorPlaceholder="error.png"
    RetryCount="3"
    RetryDelay="250"
    DownsampleHeight="300"
    ImagePath="http://lorempixel.com/output/city-q-c-600-600-5.jpg">
</ff: MvxCachedImage >

此处的示例项目:https ://github.com/molinch/FFImageLoading/tree/master/samples/

于 2015-11-24T17:13:06.823 回答
1

我的解决方案:(将图像从网络保存到本地存储并将保存的图像绑定到页面)

XAML

<ListView ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
    <DataTemplate>
        <!--Some code removed-->
        <Image Source="{Binding Img_Thumb.Result}" />
    </DataTemplate>
</ListView.ItemTemplate>

数据模型

public class DataModel_ListOfEvents
{
    public DataModel_ListOfEvents(String img_thumb)
    {
        this.Img_Thumb = new NotifyTaskCompletion<string>(JsonCached.ImageFromCache2(img_thumb));
    }
    public NotifyTaskCompletion<string> Img_Thumb { get; private set; }
}

public sealed class SampleData_ListOfEvents
{
    private static SampleData_ListOfEvents _sampleDataSource = new SampleData_ListOfEvents();

    private ObservableCollection<DataModel_ListOfEvents> _items = new ObservableCollection<DataModel_ListOfEvents>();
    public ObservableCollection<DataModel_ListOfEvents> Items { get { return this._items; } }
}

魔法

public class JsonCached
{
    public static async Task<string> ImageFromCache2(string path)
    {
        int ru = path.IndexOf(".ru") + 4;// TODO: .com .net .org
        string new_path = path.Substring(ru).Replace("/", "\\");

        StorageFolder localFolder = ApplicationData.Current.LocalFolder;
        try
        {
            Stream p = await localFolder.OpenStreamForReadAsync(new_path);
            p.Dispose();
            System.Diagnostics.Debug.WriteLine("From cache");
            return localFolder.Path + "\\" + new_path;
        }
        catch (FileNotFoundException)
        {

        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine("{0}", e.Message);
        }

        StorageFile storageFile = await localFolder.CreateFileAsync(new_path, CreationCollisionOption.OpenIfExists);

        Uri Website = new Uri(path);
        HttpClient http = new HttpClient();
        // TODO: Check connection. Return message on fail.
        System.Diagnostics.Debug.WriteLine("Downloading started");
        byte[] image_from_web_as_bytes = await http.GetByteArrayAsync(Website);

        MakeFolders(localFolder, path.Substring(ru));

        Stream outputStream = await storageFile.OpenStreamForWriteAsync();
        outputStream.Write(image_from_web_as_bytes, 0, image_from_web_as_bytes.Length);
        outputStream.Position = 0;

        System.Diagnostics.Debug.WriteLine("Write file done {0}", outputStream.Length);

        outputStream.Dispose();
        return localFolder.Path + "\\" + new_path;
    }

    private static async void MakeFolders(StorageFolder localFolder, string path)
    {
        //pics/thumbnail/050/197/50197442.jpg
        int slash = path.IndexOf("/");
        if (slash <= 0) // -1 Not found
            return;

        string new_path = path.Substring(0, slash);
        StorageFolder opened_folder = await localFolder.CreateFolderAsync(new_path, CreationCollisionOption.OpenIfExists);
        string very_new_path = path.Remove(0, new_path.Length + 1);
        MakeFolders(opened_folder, very_new_path);
    }
}

通知任务完成

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;

namespace App2.NotifyTask
{
    public sealed class NotifyTaskCompletion<TResult> : INotifyPropertyChanged
    {
        public NotifyTaskCompletion(Task<TResult> task)
        {
            Task = task;
            if (!task.IsCompleted)
            {
                var _ = WatchTaskAsync(task);
            }
        }
        private async Task WatchTaskAsync(Task task)
        {
            try
            {
                await task;
            }
            catch
            {
            }
            var propertyChanged = PropertyChanged;
            if (propertyChanged == null)
                return;
            propertyChanged(this, new PropertyChangedEventArgs("Status"));
            propertyChanged(this, new PropertyChangedEventArgs("IsCompleted"));
            propertyChanged(this, new PropertyChangedEventArgs("IsNotCompleted"));
            if (task.IsCanceled)
            {
                propertyChanged(this, new PropertyChangedEventArgs("IsCanceled"));
            }
            else if (task.IsFaulted)
            {
                propertyChanged(this, new PropertyChangedEventArgs("IsFaulted"));
                propertyChanged(this, new PropertyChangedEventArgs("Exception"));
                propertyChanged(this,
                  new PropertyChangedEventArgs("InnerException"));
                propertyChanged(this, new PropertyChangedEventArgs("ErrorMessage"));
            }
            else
            {
                propertyChanged(this,
                  new PropertyChangedEventArgs("IsSuccessfullyCompleted"));
                propertyChanged(this, new PropertyChangedEventArgs("Result"));
            }
        }
        public Task<TResult> Task { get; private set; }
        public TResult Result { get { return (Task.Status == TaskStatus.RanToCompletion) ? Task.Result : default(TResult); } }
        public TaskStatus Status { get { return Task.Status; } }
        public bool IsCompleted { get { return Task.IsCompleted; } }
        public bool IsNotCompleted { get { return !Task.IsCompleted; } }
        public bool IsSuccessfullyCompleted { get { return Task.Status == TaskStatus.RanToCompletion; } }
        public bool IsCanceled { get { return Task.IsCanceled; } }
        public bool IsFaulted { get { return Task.IsFaulted; } }
        public AggregateException Exception { get { return Task.Exception; } }
        public Exception InnerException { get { return (Exception == null) ? null : Exception.InnerException; } }
        public string ErrorMessage { get { return (InnerException == null) ? null : InnerException.Message; } }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}
于 2016-06-15T06:36:29.080 回答