SDWebImage 原理及使用問題

來源:互聯網
上載者:User

標籤:button   file   actions   rpo   dss   nis   red   做了   thread   

SDWebImage託管在github上。https://github.com/rs/SDWebImage

這個類庫提供一個UIImageView類別以支援載入來自網路的遠程圖片。具有緩衝管理、非同步下載、同一個URL下載次數控制和最佳化等特徵。

SDWebImage 載入圖片的流程
  1. 入口 setImageWithURL:placeholderImage:options: 會先把 placeholderImage 顯示,然後 SDWebImageManager 根據 URL 開始處理圖片。
  2. 進入 SDWebImageManager-downloadWithURL:delegate:options:userInfo:,交給 SDImageCache 從緩衝尋找圖片是否已經下載 queryDiskCacheForKey:delegate:userInfo:.
  3. 先從記憶體配置圖片緩衝尋找是否有圖片,如果記憶體中已經有圖片緩衝,SDImageCacheDelegate 回調 imageCache:didFindImage:forKey:userInfo: 到 SDWebImageManager。
  4. SDWebImageManagerDelegate 回調 webImageManager:didFinishWithImage: 到 UIImageView+WebCache 等前端展示圖片。
  5. 如果記憶體緩衝中沒有,產生 NSInvocationOperation 添加到隊列開始從硬碟尋找圖片是否已經緩衝。
  6. 根據 URLKey 在硬碟緩衝目錄下嘗試讀取圖片檔案。這一步是在 NSOperation 進行的操作,所以回主線程進行結果回調 notifyDelegate:。
  7. 如果上一操作從硬碟讀取到了圖片,將圖片添加到記憶體緩衝中(如果空閑記憶體過小,會先清空記憶體緩衝)。SDImageCacheDelegate 回調 imageCache:didFindImage:forKey:userInfo:。進而回調展示圖片。
  8. 如果從硬碟緩衝目錄讀取不到圖片,說明所有緩衝都不存在該圖片,需要下載圖片,回調 imageCache:didNotFindImageForKey:userInfo:。
  9. 共用或重建一個下載器 SDWebImageDownloader 開始下載圖片。
  10. 圖片下載由 NSURLConnection 來做,實現相關 delegate 來判斷圖片下載中、下載完成和下載失敗。
  11. connection:didReceiveData: 中利用 ImageIO 做了按圖片下載進度載入效果。
  12. connectionDidFinishLoading: 資料下載完成後交給 SDWebImageDecoder 做圖片解碼處理。
  13. 圖片解碼處理在一個 NSOperationQueue 完成,不會拖慢主線程 UI。如果有需要對下載的圖片進行二次處理,最好也在這裡完成,效率會好很多。
  14. 在主線程 notifyDelegateOnMainThreadWithInfo: 宣告解碼完成,imageDecoder:didFinishDecodingImage:userInfo: 回調給 SDWebImageDownloader。
  15. imageDownloader:didFinishWithImage: 回調給 SDWebImageManager 告知圖片下載完成。
  16. 通知所有的 downloadDelegates 下載完成,回調給需要的地方展示圖片。
  17. 將圖片儲存到 SDImageCache 中,記憶體緩衝和硬碟緩衝同時儲存。寫檔案到硬碟也在以單獨 NSInvocationOperation 完成,避免拖慢主線程。
  18. SDImageCache 在初始化的時候會註冊一些訊息通知,在記憶體警告或退到背景時候清理記憶體配置圖片緩衝,應用結束的時候清理到期圖片。
  19. SDWI 也提供了 UIButton+WebCache 和 MKAnnotationView+WebCache,方便使用。
  20. SDWebImagePrefetcher 可以預先下載圖片,方便後續使用
SDWebImage庫的作用

通過對UIImageView的類別擴充來實現非同步載入替換圖片的工作。

主要用到的對象:
1、UIImageView (WebCache)類別,入口封裝,實現讀取圖片完成後的回調
2、SDWebImageManager,對圖片進行管理的中轉站,記錄那些圖片正在讀取。
向下層讀取Cache(調用SDImageCache),或者向網路讀取對象(調用SDWebImageDownloader) 。
實現SDImageCache和SDWebImageDownloader的回調。
3、SDImageCache,根據URL的MD5摘要對圖片進行儲存和讀取(實現存在記憶體中或者存在硬碟上兩種實現)
實現圖片和記憶體清理工作。
4、SDWebImageDownloader,根據URL向網路讀取資料(實現部分讀取和全部讀取後再通知回調兩種方式)

其他類:
SDWebImageDecoder,非同步對映像進行了一次解壓??

解惑

1、SDImageCache是怎麼做資料管理的?
SDImageCache分兩個部分,一個是記憶體層面的,一個是硬碟層面的。
記憶體層面的相當是個緩衝器,以Key-Value的形式儲存圖片。當記憶體不夠的時候會清除所有緩衝圖片。
用搜尋檔案系統的方式做管理,檔案替換方式是以時間為單位,剔除時間大於一周的圖片檔案。
當SDWebImageManager向SDImageCache要資源時,先搜尋記憶體層面的資料,如果有直接返回,沒有的話去訪問磁碟,將圖片從磁碟讀取出來,然後做Decoder,將圖片對象放到記憶體層面做備份,再返回調用層。

2、為啥必須做Decoder?
通過這個部落格:http://www.cocoanetics.com/2011/10/avoiding-image-decompression-sickness/
現在明白了,由於UIImage的imageWithData函數是每次畫圖的時候才將Data解壓成ARGB的映像,
所以在每次畫圖的時候,會有一個解壓操作,這樣效率很低,但是只有瞬時的記憶體需求。
為了提高效率通過SDWebImageDecoder將封裝在Data下的資源解壓,然後畫在另外一張圖片上,這樣這張新圖片就不再需要重複解壓了。

這種做法是典型的空間換時間的做法。

 

參考:http://blog.csdn.net/huang2009303513/article/details/41363035

 3、當圖片在(記憶體緩衝/本地disk緩衝)緩衝中存在的時候,url指向的後台伺服器中的圖片被換掉了,這個時候SD如何獲知圖片發生了變化,如何擷取最新的正確的圖片?

自己在項目中遇到了這個問題,登陸事件的時候會請求首頁的頭像圖片,並進行緩衝到了本地disk,但是後台會有操作更換了頭像,如果沒有退出登陸(會清除本地disk的緩衝)再次登陸,圖片就一直用的本機快取的,只有再次登陸的時候才會請求到新的頭像。

這個問題,SD給了這個

如果要解決這個問題,那麼在使用SD的時候用添加了一個SDWebImageReFreshCached標記的方法,相對於沒有標記的方法,這個方法會相對來說降低效能,但是可以即時使用到最新正確的映像。

其實現原理:

 option有11種情況

typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {

    /**

     * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won‘t keep trying.

     * This flag disable this blacklisting.

     */

    SDWebImageRetryFailed = 1 << 0,

 

    /**

     * By default, image downloads are started during UI interactions, this flags disable this feature,

     * leading to delayed download on UIScrollView deceleration for instance.

     */

    SDWebImageLowPriority = 1 << 1,

 

    /**

     * This flag disables on-disk caching

     */

    SDWebImageCacheMemoryOnly = 1 << 2,

 

    /**

     * This flag enables progressive download, the image is displayed progressively during download as a browser would do.

     * By default, the image is only displayed once completely downloaded.

     */

    SDWebImageProgressiveDownload = 1 << 3,

 

    /**

     * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed.

     * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation.

     * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics.

     * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image.

     *

     * Use this flag only if you can‘t make your URLs static with embedded cache busting parameter.

     */

    SDWebImageRefreshCached = 1 << 4,

 

    /**

     * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for

     * extra time in background to let the request finish. If the background task expires the operation will be cancelled.

     */

    SDWebImageContinueInBackground = 1 << 5,

 

    /**

     * Handles cookies stored in NSHTTPCookieStore by setting

     * NSMutableURLRequest.HTTPShouldHandleCookies = YES;

     */

    SDWebImageHandleCookies = 1 << 6,

 

    /**

     * Enable to allow untrusted SSL certificates.

     * Useful for testing purposes. Use with caution in production.

     */

    SDWebImageAllowInvalidSSLCertificates = 1 << 7,

 

    /**

     * By default, image are loaded in the order they were queued. This flag move them to

     * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which 

     * could take a while).

     */

    SDWebImageHighPriority = 1 << 8,

    

    /**

     * By default, placeholder images are loaded while the image is loading. This flag will delay the loading

     * of the placeholder image until after the image has finished loading.

     */

    SDWebImageDelayPlaceholder = 1 << 9,

 

    /**

     * We usually don‘t call transformDownloadedImage delegate method on animated images,

     * as most transformation code would mangle it.

     * Use this flag to transform them anyway.

     */

    SDWebImageTransformAnimatedImage = 1 << 10,

    

    /**

     * By default, image is added to the imageView after download. But in some cases, we want to

     * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance)

     * Use this flag if you want to manually set the image in the completion when success

     */

    SDWebImageAvoidAutoSetImage = 1 << 11

};

 

 

  

SDWebImage 原理及使用問題

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.