前言
內容目錄
- ImageLoader設計原理
- ImageLoader流程圖
- ImageLoader的使用
- ImageLoader優化
- Fresco介紹
- 圖片策略優化
- 小結
ImageLoader設計原理
ImageLoader的工作原理:在顯示圖片的時,它會先在內存中查找,如果沒有就去本地查找,如果還沒有,就開一個新的線程去下載這張圖片,下載成功會把圖片同時緩存在內存和本地。


ImageLoader流程圖

ImageLoader的使用
- ImagaLoaderConfiguaration——對圖片緩存進行總體配置,包含內存緩存的大小,本地緩存的大小和位置、日志、下載策略(FIFO還是LIFO)等。
- ImageLoader——一般使用displayImage來把URL對應的圖片顯示在ImageView上。
- DisplayImageOptions——在每個頁面需要顯示圖片的地方,控制如何顯示的細節,比如指定下載時的默認圖、是否將緩存放到內存或本地磁盤。
從三者的協作關系上看,他們有點像廚房規定、廚師、客戶個人口味之間的關系。ImageLoaderConfiguration就像是廚房里面的規定,每一個廚師要怎么着裝,要怎么保持廚房的干凈,這是針對每一個廚師都適用的規定,而且不允許個性化改變。ImageLoader就像是具體做菜的廚師,負責具體菜譜的制作。DisplayImageOptions就像每個客戶的偏好,根據客戶是重口味還是清淡,每一個imageLoader根據DisplayImageOptions的要求具體執行。
ImagaLoaderConfiguaration
// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.// See the sample project how to use ImageLoader correctly.File cacheDir =StorageUtils.getCacheDirectory(context); ImageLoaderConfiguration config =newImageLoaderConfiguration.Builder(context) .memoryCacheExtraOptions(480, 800) // default = device screen dimensions .diskCacheExtraOptions(480, 800, null) .taskExecutor(...) .taskExecutorForCachedImages(...) .threadPoolSize(3) // default .threadPriority(Thread.NORM_PRIORITY-2) // default .tasksProcessingOrder(QueueProcessingType.FIFO) // default .denyCacheImageMultipleSizesInMemory() .memoryCache(newLruMemoryCache(2*1024*1024)) .memoryCacheSize(2*1024*1024) .memoryCacheSizePercentage(13) // default .diskCache(newUnlimitedDiskCache(cacheDir)) // default .diskCacheSize(50*1024*1024) .diskCacheFileCount(100) .diskCacheFileNameGenerator(newHashCodeFileNameGenerator()) // default .imageDownloader(newBaseImageDownloader(context)) // default .imageDecoder(newBaseImageDecoder()) // default .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default .writeDebugLogs() .build();
DisplayImageOptions
每一個ImageLoader.displayImage(...)都可以使用DisplayImageOptions,具體配置代碼如下:
// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using. // See the sample project how to use ImageLoader correctly. DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.ic_stub) // resource or drawable .showImageForEmptyUri(R.drawable.ic_empty) // resource or drawable .showImageOnFail(R.drawable.ic_error) // resource or drawable .resetViewBeforeLoading(false) // default .delayBeforeLoading(1000) .cacheInMemory(false) // default .cacheOnDisk(false) // default .preProcessor(...) .postProcessor(...) .extraForDownloader(...) .considerExifParams(false) // default .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default .bitmapConfig(Bitmap.Config.ARGB_8888) // default .decodingOptions(...) .displayer(new SimpleBitmapDisplayer()) // default .handler(new Handler()) // default .build();
ImageLoader
ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance // Load image, decode it to Bitmap and display Bitmap in ImageView (or any other view // which implements ImageAware interface) imageLoader.displayImage(imageUri, imageView);
// Load image, decode it to Bitmap and return Bitmap to callback imageLoader.loadImage(imageUri, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { // Do whatever you want with Bitmap } });
ImageLoader優化
protected void onDestroy() { //回收該頁面緩存在內存的圖片 imageLoader.clearMemoryCache(); super.onDestroy(); }
Fresco介紹
Fresco 是一個強大的圖片加載組件。它是Facebook開源的圖片加載庫
Fresco 中設計有一個叫做 image pipeline 的模塊。它負責從網絡,從本地文件系統,本地資源加載圖片。為了最大限度節省空間和CPU時間,它含有3級緩存設計(2級內存,1級文件)。
Fresco 中設計有一個叫做 Drawees 模塊,方便地顯示loading圖,當圖片不再顯示在屏幕上時,及時地釋放內存和空間占用。
Fresco 支持 Android2.3(API level 9) 及其以上系統。


為了下載網絡圖片,請確保在 AndroidManifest.xml
中有以下權限:
<uses-permission android:name="android.permission.INTERNET"/>
在 Application 初始化時,在應用調用 setContentView()
之前,進行初始化:
Fresco.initialize(context);
在xml布局文件中, 加入命名空間:
<!-- 其他元素 --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:fresco="http://schemas.android.com/apk/res-auto"> 加入SimpleDraweeView: <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/my_image_view" android:layout_width="20dp" android:layout_height="20dp" fresco:placeholderImage="@drawable/my_drawable" />
開始加載圖片
Uri uri = Uri.parse("https://raw.githubusercontent.com/facebook/fresco/gh-pages/static/fresco-logo.png"); SimpleDraweeView draweeView = (SimpleDraweeView) findViewById(R.id.my_image_view); draweeView.setImageURI(uri);
圖片策略優化
- 要確保下載的每張圖,都符合ImageView控件的大小。可以事先准備很多套不同的分辨率的圖片,然后每次根據URL請求圖片時,都要額外在URL上加兩個參數,width和height,從而要求服務器返回其中某一個張圖,比如:http://www.aaa.com/a.png?width=100&height=50
- 低流量模式。在2G和3G網絡環境下,我們應該適當降低圖片的質量,降低圖片質量,相應的圖片大小也會降低,簡稱低流量模式,比如在請求網址中再添加一個參數,叫做quality,在2G網絡下這個值為50%,在3G網絡情況下,這個值為70%,這樣就會將JPG圖片質量降低為50%或70%。
- 極速模式。發現在2G和3G網絡環境下,大部分用戶對圖片不感興趣,我們可以設計一些只有文字的頁面,這種頁面稱呼為極速模式,以節省流量。
小結
本篇主要介紹了第三方圖片加載庫的原理和使用方法,特別是ImageLoader的介紹,因為圖片顯示在APP中是很常見的應用場景,況且ImageLoader已經封裝好了一些類和方法。我們可以直接拿來用了。而不用重復去寫了。如果自己去寫一個的話,這方面的程序還是比較麻煩的,要考慮多線程緩存,內存溢出等很多方面,再說這么多程序都在用,說明穩定性還是可靠的,類似這種工具類能用穩定成熟的,我們作為一名開發人員,專注度還是在應用業務開發上。