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

自己寫一個輕量級圖片載入類:LruCache 與大圖壓縮實作

編輯:關於 Android 程式設計

成熟方案很多——nostra13 的 Image-Loader、xUtils、Facebook 的 Fresco——但做專案時有載入需求,自己刻一遍最能理解原理。以下是一個只處理本地圖片、聚焦快取與壓縮的輕量實作。

牽涉到的四個知識點

LruCache 記憶體快取、ExecutorService 背景執行、BitmapFactory 的 inJustDecodeBounds 解碼技巧,以及 view.setTag() 防止清單圖片錯位。這四件事幾乎是所有自製圖片載入器的共同骨架。

呼叫方式

// 本地照片絕對路徑
String imageUrl = (String) t;
ImageView grid_item = holder.getView(R.id.grid_item);

// 設定 tag 作為標記,用來避免圖片顯示錯位
grid_item.setTag(imageUrl);

/**
 * 顯示圖片
 * @param context   上下文
 * @param imageView ImageView 控制項
 * @param sourcePath 圖片位址
 * @param r_Id      預設圖片 id,例如 R.drawable.img_bg
 * @param callback   圖片顯示回呼
 */
new ImageLoader().displayBmp(mContext, grid_item, imageUrl, R.drawable.img_bg, this);

LruCache 快取

手機記憶體有限,不可能把所有圖片都放進記憶體。Android 提供的 LruCache 採用「近期最少使用」演算法:圖片不斷加入快取,最久未被使用的那張就被淘汰,藉此避免記憶體不足。

public ImageLoader() {
    // 取應用記憶體的 1/8 作為圖片快取
    int cacheSize = maxMemory / 8;
    mLruCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getByteCount();
        }
    };
}

/** 將圖片存入 LruCache */
public void putBitmapToLruCache(String key, Bitmap bitmap) {
    if (getBitmapFromLruCache(key) == null && mLruCache != null) {
        mLruCache.put(key, bitmap);
    }
}

/** 從 LruCache 取得圖片 */
public Bitmap getBitmapFromLruCache(String key) {
    return mLruCache.get(key);
}

用法和 HashMap 一樣,put 進去、get 出來,差別只在容量滿時會自動淘汰舊項目。這裡刻意重寫 sizeOf,讓容量計算以位元組而非項目數量為單位。

載入流程

public void displayBmp(final Context context, final ImageView imageView,
                       final String sourcePath, final int r_Id,
                       final ImageCallback callback) {
    final String path;
    if (!TextUtils.isEmpty(sourcePath)) {
        path = sourcePath;
    } else {
        return;
    }

    // 先試著從快取取得圖片,path 作為 key
    Bitmap bmp = mLruCache.get(path);
    if (bmp != null) {
        if (callback != null) {
            callback.imageLoad(imageView, bmp, sourcePath);
        }
        return;
    }

    // 快取沒有,先顯示預設圖
    imageView.setImageResource(r_Id);

    // 啟動執行緒池載入
    threadPoolUtils.getExecutorService().execute(new Runnable() {
        Bitmap bitmap = null;

        @Override
        public void run() {
            try {
                bitmap = revitionImageSize(imageView, sourcePath); // 載入縮圖
            } catch (Exception e) { }

            if (bitmap == null) {
                try {
                    // 縮圖載入失敗,改用預設圖
                    bitmap = BitmapFactory.decodeResource(context.getResources(), r_Id);
                } catch (Exception e) { }
            }

            if (path != null && bitmap != null) {
                putBitmapToLruCache(path, bitmap); // 寫回快取
            }

            if (callback != null) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.imageLoad(imageView, bitmap, sourcePath);
                    }
                });
            }
        }
    });
}

流程不複雜:先查快取,命中就直接回呼;未命中先顯示預設圖佔位,把解碼丟進執行緒池,完成後寫回快取並切回主執行緒更新。

大圖壓縮:revitionImageSize()

public Bitmap revitionImageSize(ImageView imageView, String path) throws IOException {
    // 取得版面配置中 ImageView 的寬高
    int img_width = imageView.getWidth();
    int img_height = imageView.getHeight();

    BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(path)));
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;              // 只讀邊界,不解碼像素
    BitmapFactory.decodeStream(in, null, options);
    in.close();

    int height = options.outHeight;
    int width = options.outWidth;
    Bitmap bitmap = null;
    int inSampleSize = 1;

    // 計算實際寬高與目標寬高的比率
    final int heightRatio = Math.round((float) height / (float) img_height);
    final int widthRatio = Math.round((float) width / (float) img_width);

    // 取寬高比率中較小者,確保最終圖片寬高都大於等於目標
    inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

    options.inSampleSize = inSampleSize;
    options.inJustDecodeBounds = false;             // 這次真的解碼
    in = new BufferedInputStream(new FileInputStream(new File(path)));
    bitmap = BitmapFactory.decodeStream(in, null, options);
    in.close();
    return bitmap;
}

inJustDecodeBounds 的巧妙之處

關鍵在於第一次呼叫時把 inJustDecodeBounds 設為 true:這時候程式並沒有真正把圖片載入記憶體,只是讀取檔案頭,但我們已經拿到了 options.outHeight 與 options.outWidth。有了尺寸資訊就能算出該縮到幾分之幾,接著把 inJustDecodeBounds 設回 false 再解碼一次,這次才產生縮小後的 Bitmap。用兩次解碼換取記憶體安全,是很常見也很划算的交易。

回呼介面與錯位問題

/** 顯示圖片回呼 */
public interface ImageCallback {
    void imageLoad(ImageView imageView, Bitmap bitmap, Object... params);
}

回呼的實作寫在顯示圖片的地方,這裡有個不能省的判断:

/** 圖片快取回呼 */
@Override
public void imageLoad(ImageView imageView, Bitmap bitmap, Object... params) {
    if (imageView != null && bitmap != null) {
        String url = (String) params[0];
        // 比對此處的 url 是否等於 imageView.getTag()
        // 若去掉這個判斷,就會出現清單圖片顯示錯位的經典問題
        if (url != null && url.equals((String) imageView.getTag())) {
            ((ImageView) imageView).setImageBitmap(bitmap);
        }
    }
}

原因很單純:ImageView 在 ListView/GridView 中會被回收重用,A 位置的 view 可能在你等待解碼時被拿去顯示 B 的內容。若不比對 tag,A 的圖片就會蓋到 B 上,這正是滑動清單時圖片亂竄的成因。

使用方式

專案已發佈到 JitPack,加入依賴即可:

dependencies {
    compile 'com.zts:imageloader:1.1.1'
}

原始碼在 GitHub 上,下載下來跑一次會比只看程式碼好理解。若要繼續打磨,優先順序建議是:把每次 new ImageLoader() 改成單例(否則快取永遠命中不到)、加上 Disk LruCache 做磁碟快取、以及處理 HTTP 圖片的快取與重試。

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