在以前的文章中,我讲到了一些关于Windows Phone中处理图片的知识,Windows Phone 中编辑图片 、Windows Phone 中处理图片的技巧 、在Windows Phone显示GIF图片 、保存图片及加载图片 ,能够看出图片处理在Windows Phone 开发中占了比较大的比例,今天我介绍一个简单的图片缓存机制。html
David Anson 发表一个LowProfileImageLoader , 用来下载图片而不影响UI线程(Mango中已经将图片处理从UI线程中抽离处理了,因此不会有这个影响,你们也能够参考这篇文章).web
LowProfileImageLoader 的思路是将图片的Uri都放入到一个队列中,而后依次遍历这个队列去请求图片资源,下载好后通知UI将流返回,每当有新UI插入进来后都会唤醒工做线程, 而且咱们能够设置工做线程一次能够同时对几个Uri进行处理,默认是5个。windows
理解了 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回调了。app
在回调中增长处理,若是没有缓存的,须要将图片进行缓存ide
// Decode the p_w_picpath 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 p_w_picpath decode exceptions (ex: invalid p_w_picpath) } }
下面的方法是判断图片有没有缓存的post
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进行相应的转码:this
private static string GetParsePath(string url) { return url.Replace("://", "").Replace("/","_"); }
下面的方法是从缓存中读取图片流的url
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.