Windows Phone 实用开发技巧(28):图片缓存

在之前的文章中,我讲到了一些关于Windows Phone中处理图片的知识,Windows Phone 中编辑图片Windows Phone 中处理图片的技巧在Windows Phone显示GIF图片保存图片及加载图片 ,可以看出图片处理在Windows Phone 开发中占了比较大的比例,今天我介绍一个简单的图片缓存机制。

David Anson 发表一个LowProfileImageLoader , 用来下载图片而不影响UI线程(Mango中已经将图片处理从UI线程中抽离处理了,所以不会有这个影响,大家也可以参考这篇文章).

LowProfileImageLoader 的思路是将图片的Uri都放入到一个队列中,然后依次遍历这个队列去请求图片资源,下载好后通知UI将流返回,每当有新UI插入进来后都会唤醒工作线程,并且我们可以设置工作线程一次可以同时对几个Uri进行处理,默认是5个。

理解了 LowProfileImageLoader 的思路后,我们依据 LowProfileImageLoader 定制一个简单的图片缓存,即如果我们已经下载过这张图片了,我们就把图片保存到本地,等到下次启动程序的时候,判断本地是否已经缓存过该图片,如果缓存过该图片,就从本地读取图片返回;如果没有缓存过该图片,则下载完后通知UI,然后将图片保存至本地。

在线程工作的主方法WorkerThreadProc中的请求网络之前增加判断,判断该图片是否缓存

if (pendingRequest.Uri.IsAbsoluteUri)
{
    //load from isolated storage if has been cached
    if (IsImageCached(pendingRequest.Uri))
    {
        if (null!=LoadCachedImage(pendingRequest.Uri))
        {
            pendingCompletions.Enqueue(new PendingCompletion(pendingRequest.Image, pendingRequest.Uri, LoadCachedImage(pendingRequest.Uri)));
        }
    }
    else
    {
        // Download from network
        var webRequest = HttpWebRequest.CreateHttp(pendingRequest.Uri);
        webRequest.AllowReadStreamBuffering = true; // Don't want to block this thread or the UI thread on network access
        webRequest.BeginGetResponse(HandleGetResponseResult, new ResponseState(webRequest, pendingRequest.Image, pendingRequest.Uri));
    }                        
}

如果已经缓存了,直接推入到完成队列中,也就是准备向UI回调了。

在回调中增加处理,如果没有缓存的,需要将图片进行缓存

// Decode the image and set the source
var pendingCompletion = pendingCompletions.Dequeue();
if (GetUriSource(pendingCompletion.Image) == pendingCompletion.Uri)
{
    //if has been cached,do not cache
    if (!IsImageCached(pendingCompletion.Uri))
    {
        CacheImage(pendingCompletion.Stream, pendingCompletion.Uri);
    }
    try
    {
        ImageSource bitmap;
        var bitmapImage = new BitmapImage();
        bitmapImage.SetSource(pendingCompletion.Stream);
        bitmap = bitmapImage;
        pendingCompletion.Image.Source = bitmap;
    }
    catch(Exception ex)
    {
        // Ignore image decode exceptions (ex: invalid image)
    }
}

下面的方法是判断图片有没有缓存的

private static bool IsImageCached(Uri u)
{
    string filePath = Path.Combine(Constants.CACHE_DIR_IMAGES, GetParsePath(u.ToString()));
    using (var store=IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (store.FileExists(filePath))
        {
            return true;
        }
    }
    return false;
}

其中涉及到将图片的uri解析的问题,因为一般图片的uri都是http://….jpg之类的,为了避免不必要的麻烦,需要将uri进行相应的转码:

private static string GetParsePath(string url)
{
    return url.Replace("://", "").Replace("/","_");
}

下面的方法是从缓存中读取图片流的

private static Stream LoadCachedImage(Uri u)
{
    string filePath = Path.Combine(Constants.CACHE_DIR_IMAGES, GetParsePath(u.ToString()));
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (!store.FileExists(filePath))
        {
            return null;
        }
        return store.OpenFile(filePath, FileMode.Open, FileAccess.Read);
    }
}

以及将图片缓存的方法:

private static bool CacheImage(Stream source,Uri u)
{
    string filePath = Path.Combine(Constants.CACHE_DIR_IMAGES, GetParsePath(u.ToString()));
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        try
        {
            if (!store.DirectoryExists(Constants.CACHE_DIR_IMAGES))
            {
                store.CreateDirectory(Constants.CACHE_DIR_IMAGES);
            }
            using (var stream = store.OpenFile(filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                byte[] bytes = new byte[source.Length];
                source.Read(bytes, 0, (int)source.Length);
                stream.Write(bytes, 0, (int)source.Length);
            }
            return true;
        }
        catch (Exception)
        {
            return false;
            throw;
        }
    }
}

调用方法是这样的

<Image delay:LowProfileImageLoader.UriSource="{Binding logo}" Grid.Column="0" Height="100" Width="100" />

在XAML中的Image中添加如上的代码即可,这样只要图片一被下载,就会被缓存到本地,以便下次使用。

当然你可以加上一个依赖属性,判断当前是否启动缓存。另外一个需要考虑的是,何时删除图片缓存,那由你的app决定!

修改后的LowProfileImageLoader可以在这里找到。Hope that helps.

posted @ 2011-11-17 21:21  Alexis  阅读(4968)  评论(11编辑  收藏  举报