Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 圖片載入框架選型:從自寫 ImageLoader 到 Glide、Fresco、Picasso

編輯:關於 Android 程式設計

Android 生態爆發之後,自定義控制項與第三方框架大量湧現。回想 2011 年前後,專案裡的 UI 幾乎全靠系統原生控制項,動畫與版面都很樸素,網路請求一律用 HttpClient,圖片則是「下載完再顯示」——當時的開源資源遠不如現在豐富。

從工程角度看,App 架構恆久不變的兩大支柱是:網路通訊框架與圖片載入框架。通訊部分已有 async-http、okhttp 等選擇,而 Volley 則同時涵蓋兩者,不少人為了省事整套採用;Facebook 的 Fresco 同樣自帶網路與圖片能力,品質相當不錯。

一、當年我們自己寫的 ImageLoader

public class ImageDownloader {

    private static ImageDownloader instance = null;
    private static File cacheDir;
    public static Map<String, SoftReference<Bitmap>> bitMapCache = new HashMap<>();

    public static ImageDownloader getInstance() {
        if (instance == null) {
            instance = new ImageDownloader();
        }
        return instance;
    }

    private ImageDownloader() {
        // 決定快取目錄:優先外部儲存,其次應用私有目錄
        if (android.os.Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED)) {
            cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "WholeMag");
        } else {
            cacheDir = WholeMagApplication.getInstance().getCacheDir();
        }
        if (!cacheDir.exists()) { cacheDir.mkdirs(); }
    }

    public void download(String actName, String url, ImageView imageView) {
        new BitmapDownloaderTask(imageView, actName).execute(url);
    }

    class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {

        private final WeakReference<ImageView> imageViewReference; // 用弱引用避免記憶體洩漏
        private String actName;

        BitmapDownloaderTask(ImageView imageView, String actName) {
            imageViewReference = new WeakReference<ImageView>(imageView);
            this.actName = actName;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap rebmp = getLocalBitmap(params[0], actName);
            if (rebmp == null) { rebmp = downloadBitmap(params[0], actName); }
            return rebmp;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (isCancelled() || bitmap == null) { return; }
            ImageView imageView = imageViewReference.get();
            if (imageView == null) { return; }

            // 依裝置寬度等比放大,並加上淡入動畫
            double widthX = (float) WholeMagDatas.getDeviceWidth() / bitmap.getWidth();
            int bitmapHight = bitmap.getHeight();
            imageView.setImageBitmap(bitmap);
            if (actName.equals(AppData.NEWS_DETAIL_ACT)) {
                imageView.setLayoutParams(new FrameLayout.LayoutParams(
                        android.view.ViewGroup.LayoutParams.FILL_PARENT,
                        (int) (bitmapHight * widthX), Gravity.CENTER));
            }
            AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
            alphaAnimation.setDuration(500);
            imageView.startAnimation(alphaAnimation);
        }
    }

    /** 先讀本地快取 */
    static Bitmap getLocalBitmap(String url, String actName) {
        if (bitMapCache.containsKey(url)) {
            return bitMapCache.get(url).get();
        }
        File f = Tools.getFile(actName, url);
        InputStream inputStream = null;
        try {
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inPreferredConfig = Bitmap.Config.RGB_565; // 每像素 2 位元組,省一半記憶體
            o.inDither = false;
            o.inPurgeable = true;
            inputStream = new FileInputStream(f);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, o);
            bitMapCache.put(url, new SoftReference<Bitmap>(bitmap));
            return bitmap;
        } catch (Exception e) {
            // 忽略,回傳 null 交由上層重試
        } finally {
            if (inputStream != null) {
                try { inputStream.close(); } catch (Exception ex) { }
            }
        }
        return null;
    }

    /** 從網路下載並落地 */
    static Bitmap downloadBitmap(String url, String actName) {
        final AndroidHttpClient client = AndroidHttpClient.newInstance("linux");
        final HttpGet getRequest = new HttpGet(url);
        try {
            HttpResponse response = client.execute(getRequest);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity == null) { return null; }

            File f = Tools.getFile(actName, url);
            OutputStream os = new FileOutputStream(f);
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inPreferredConfig = Bitmap.Config.RGB_565;
                o.inDither = false;
                o.inPurgeable = true;
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, o);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                bitMapCache.put(url, new SoftReference<Bitmap>(bitmap));
                return bitmap;
            } finally {
                if (inputStream != null) { inputStream.close(); }
                if (os != null) { os.close(); }
                entity.consumeContent();
            }
        } catch (Exception e) {
            getRequest.abort();
        } finally {
            if (client != null) { client.close(); }
        }
        return null;
    }
}

當時為了避免圖片把記憶體撐爆而 OOM,快取一律使用軟引用(SoftReference),效果還算不錯。歸納起來,圖片載入的基本原理就是:把 url 與 ImageView 配對拋進背景執行緒,下載 byte 流後 decode 成 Bitmap,最後切回 UI 執行緒設定到 ImageView 上。

這版實作的不足也很明顯:只做應用層快取、沒有標準化的磁碟快取策略;沒有依目標尺寸做 decode 縮放,也沒有統一設定色彩格式,記憶體使用不夠精緻。後來的 LruCache 思路與此類似,但多了「限制快取總容量」與「依使用頻率淘汰」兩項關鍵設計,並把記憶體層與 SD 卡層各自封裝。

二、成熟框架的設定項:以 ImageLoader 為例

把開源 universal-image-loader 的 ImageLoaderConfiguration 攤開來看,就能理解一個完整框架要照顧多少細節:

public final class ImageLoaderConfiguration {
    final Resources resources;   // 計算圖片尺寸時需要螢幕寬高
    final int maxImageWidthForMemoryCache;   // 記憶體快取允許的最大寬
    final int maxImageHeightForMemoryCache;  // 記憶體快取允許的最大高
    final int maxImageWidthForDiskCache;     // 磁碟快取允許的最大寬
    final int maxImageHeightForDiskCache;    // 磁碟快取允許的最大高
    final BitmapProcessor processorForDiskCache; // 從磁碟讀出的後處理器
    final Executor taskExecutor;                 // 載入圖片的執行緒池
    final Executor taskExecutorForCachedImages;  // 載入快取圖片的執行緒池
    final boolean customExecutor;                // 是否自訂執行緒池
    final boolean customExecutorForCachedImages;
    final int threadPoolSize;        // 核心線程數,可控制當前頁面的併發載入量
    final int threadPriority;        // 線程優先級
    final QueueProcessingType tasksProcessingType; // LIFO 或 FIFO
    final MemoryCache memoryCache;   // 記憶體快取實作
    final DiskCache diskCache;       // 磁碟快取實作
    final ImageDownloader downloader;   // 依 http/file/content/drawable/asset 分派
    final ImageDecoder decoder;         // 把位元組解析成 Bitmap
    final DisplayImageOptions defaultDisplayImageOptions;
    final ImageDownloader networkDeniedDownloader; // 僅離線載入(等同讀 SD 卡)
    final ImageDownloader slowNetworkDownloader;   // 慢網路最佳化
}

而每一次載入的行為,則由 DisplayImageOptions 決定:

public final class DisplayImageOptions {
    private final int imageResOnLoading;      // 載入中的佔位圖資源
    private final int imageResForEmptyUri;    // url 為空時的圖
    private final int imageResOnFail;         // 載入失敗時的圖
    private final Drawable imageOnLoading;
    private final Drawable imageForEmptyUri;
    private final Drawable imageOnFail;
    private final boolean resetViewBeforeLoading; // 載入前是否重置(放棄舊請求)
    private final boolean cacheInMemory;          // 是否記憶體快取
    private final boolean cacheOnDisk;            // 是否磁碟快取
    private final ImageScaleType imageScaleType;  // 縮放策略
    private final Options decodingOptions;        // BitmapFactory.Options
    private final int delayBeforeLoading;         // 延遲載入,適合非當前頁
    private final boolean considerExifParams;     // 是否套用 EXIF 旋轉/翻轉
    private final Object extraForDownloader;      // 傳給下載器的額外參數
    private final BitmapProcessor preProcessor;   // 快取未命中時的前處理
    private final BitmapProcessor postProcessor;  // 快取命中時的後處理
    private final BitmapDisplayer displayer;      // 顯示動畫
    private final Handler handler;                // 與主線程溝通
    private final boolean isSyncLoading;          // 是否同步載入
}

此外它還支援以像素為單位指定佔位尺寸,讓框架在 decode 階段就能縮放到目標大小,避免把大圖整個讀進記憶體。

三、主流框架的差異

  • Fresco(Facebook):最大優勢是能把載入過程拆成「載入前、載入中、載入後、失敗」等多個階段自訂圖片,還能輕鬆設定圓角、圓形等形狀;管線化程度最高,適合圖片量大、對記憶體敏感的頁面。
  • Picasso(Square):載入速度快,因為預設的 Bitmap 格式佔用記憶體較小;API 簡潔,對 ListView/RecyclerView 的圖片錯位問題處理得很成熟。
  • Glide:被視為 Picasso 的進化版,最大的差異是能與 Activity/Fragment 生命週期綁定,頁面銷毀時自動取消請求;同時在解碼策略與快取預設上更積極,列表體驗通常更順。
  • Volley:在早期 ImageLoader 概念上再封裝一層,差異不大,但把網路請求隊列、快取與重試機制整合進來,功能上對圖片部分反而略為弱化。
  • universal-image-loader:功能最完整的「全能型」選手,設定項如上所述幾乎涵蓋所有想像得到的場景,缺點是 API 相對繁瑣、維護節奏較慢。

這些框架大多誕生於 universal-image-loader 之後,因此設計上多少受其影響。就原創性而言,真正跳脫既有框架思維的主要是 Fresco(分階段管線與自訂 Drawee)與 Glide(生命週期感知)。

選型建議

如果是新專案,清單型畫面多、追求輕量與生命週期自動管理,Glide 通常是首選;需要圓形頭像、漸進式載入、GIF 與高度自訂顯示效果,Fresco 更合適;只是想快速塞圖片且團隊已熟悉,Picasso 足夠。若專案仍需維護舊版程式碼,則先確認目前使用的 API 是否已被標記為棄用(例如 Picasso.with() 已改為 Picasso.get()),再評估遷移成本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved