Windows Phone 實用開發技巧(28):圖片緩存

在以前的文章中,我講到了一些關於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.

相關文章
相關標籤/搜索