一、概述
優秀的圖片加載框架不要太多,什麼UIL , Volley ,Picasso,Imageloader等等。可是做爲一名合格的程序猿,必須懂其中的實現原理,因而乎,今天我就帶你們一塊兒來設計一個加載網絡、本地的圖片框架。有人可能會說,本身寫會不會很渣,運行效率,內存溢出神馬的。放心,咱們拿demo說話,拼得就是速度,奏事這麼任性。html
好了,若是你看過以前的博文,相似Android Handler 異步消息處理機制的妙用 建立強大的圖片加載類,可能會對接下來文章理解會有很大的幫助。沒有的話,就跟我往下繼續走吧,也不要去看了。java
關於加載本地圖片,固然了,我手機圖片比較少,7000來張:android
一、首先確定不能內存溢出,可是尼瑪如今像素那麼高,怎麼才能保證呢?我相信利用LruCache統一管理你的圖片是個不二的選擇,全部的圖片從LruCache裏面取,保證全部的圖片的內存不會超過預設的空間。緩存
二、加載速度要剛剛的,我一用力,滑動到3000張的位置,你要是還在從第一張給我加載,尼瑪,你覺得我打dota呢。因此咱們須要引入加載策略,咱們不能FIFO,咱們選擇LIFO,當前呈現給用戶的,最新加載;當前未呈現的,選擇加載。微信
三、使用方便。通常圖片都會使用GridView做爲控件,在getView裏面進行圖片加載,固然了爲了避免錯亂,可能還須要用戶去本身setTag,本身寫回調設置圖片。固然了,咱們不須要這麼麻煩,一句話IoadImage(imageview,path)便可,剩下的請交給咱們的圖片加載框架處理。網絡
作到以上幾點,關於本地的圖片加載應該就木有什麼問題了。架構
關於加載網絡圖片,其實原理差很少,就多了個是否啓用硬盤緩存的選項,若是啓用了,加載時,先從內存中查找,而後從硬盤上找,最後去網絡下載。下載完成後,別忘了寫入硬盤,加入內存緩存。若是沒有啓用,那麼就直接從網絡壓縮獲取,加入內存便可。app
二、效果圖
終於扯完了,接下來,簡單看個效果圖,關於加載本地圖片的效果圖:能夠從Android 超高仿微信圖片選擇器 圖片該這麼加載這篇博客中下載Demo運行。框架
下面演示一個網絡加載圖片的例子:異步

80多張從網絡加載的圖片,能夠看到我直接拖到最後,基本是呈如今用戶眼前的最早加載,要是從第一張到80多,估計也是醉了。
此外:圖片來自老郭的博客,感謝!!!ps:若是你以爲圖片不勁爆,Day Day Up找老郭去。
三、徹底解析
一、關於圖片的壓縮
不論是從網絡仍是本地的圖片,加載都須要進行壓縮,而後顯示:
用戶要你壓縮顯示,會給咱們什麼?一個imageview,一個path,咱們的職責就是壓縮完成後顯示上去。
一、本地圖片的壓縮
a、得到imageview想要顯示的大小
想要壓縮,咱們第一步應該是得到imageview想要顯示的大小,沒大小確定沒辦法壓縮?
那麼如何得到imageview想要顯示的大小呢?
-
-
-
-
-
-
- public static ImageSize getImageViewSize(ImageView imageView)
- {
-
- ImageSize imageSize = new ImageSize();
- DisplayMetrics displayMetrics = imageView.getContext().getResources()
- .getDisplayMetrics();
-
- LayoutParams lp = imageView.getLayoutParams();
-
- int width = imageView.getWidth();
- if (width <= 0)
- {
- width = lp.width;
- }
- if (width <= 0)
- {
-
- width = getImageViewFieldValue(imageView, "mMaxWidth");
- }
- if (width <= 0)
- {
- width = displayMetrics.widthPixels;
- }
-
- int height = imageView.getHeight();
- if (height <= 0)
- {
- height = lp.height;
- }
- if (height <= 0)
- {
- height = getImageViewFieldValue(imageView, "mMaxHeight");
- }
- if (height <= 0)
- {
- height = displayMetrics.heightPixels;
- }
- imageSize.width = width;
- imageSize.height = height;
-
- return imageSize;
- }
-
- public static class ImageSize
- {
- int width;
- int height;
- }
能夠看到,咱們拿到imageview之後:
首先企圖經過getWidth獲取顯示的寬;有些時候,這個getWidth返回的是0;
那麼咱們再去看看它有沒有在佈局文件中書寫寬;
若是佈局文件中也沒有精確值,那麼咱們再去看看它有沒有設置最大值;
若是最大值也沒設置,那麼咱們只有拿出咱們的終極方案,使用咱們的屏幕寬度;
總之,不能讓它任性,咱們必定要拿到一個合適的顯示值。
能夠看到這裏或者最大寬度,咱們用的反射,而不是getMaxWidth();維薩呢,由於getMaxWidth居然要API 16,我也是醉了;爲了兼容性,咱們採用反射的方案。反射的代碼就不貼了。
b、設置合適的inSampleSize
咱們得到想要顯示的大小,爲了什麼,還不是爲了和圖片的真正的寬高作比較,拿到一個合適的inSampleSize,去對圖片進行壓縮麼。
那麼首先應該是拿到圖片的寬和高:
-
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeFile(path, options);
這三行就成功獲取圖片真正的寬和高了,存在咱們的options裏面;
而後咱們就能夠happy的去計算inSampleSize了:
-
-
-
-
-
-
-
-
- public static int caculateInSampleSize(Options options, int reqWidth,
- int reqHeight)
- {
- int width = options.outWidth;
- int height = options.outHeight;
-
- int inSampleSize = 1;
-
- if (width > reqWidth || height > reqHeight)
- {
- int widthRadio = Math.round(width * 1.0f / reqWidth);
- int heightRadio = Math.round(height * 1.0f / reqHeight);
-
- inSampleSize = Math.max(widthRadio, heightRadio);
- }
-
- return inSampleSize;
- }
options裏面存了實際的寬和高;reqWidth和reqHeight就是咱們以前獲得的想要顯示的大小;通過比較,獲得一個合適的inSampleSize;
有了inSampleSize:
- options.inSampleSize = ImageSizeUtil.caculateInSampleSize(options,
- width, height);
-
-
- options.inJustDecodeBounds = false;
- Bitmap bitmap = BitmapFactory.decodeFile(path, options);
- return bitmap;
通過這幾行,就完成圖片的壓縮了。
上述是本地圖片的壓縮,那麼若是是網絡圖片呢?
二、網絡圖片的壓縮
a、直接下載存到sd卡,而後採用本地的壓縮方案。這種方式當前是在硬盤緩存開啓的狀況下,若是沒有開啓呢?
b、使用BitmapFactory.decodeStream(is, null, opts);
-
-
-
-
-
-
-
- public static Bitmap downloadImgByUrl(String urlStr, ImageView imageview)
- {
- FileOutputStream fos = null;
- InputStream is = null;
- try
- {
- URL url = new URL(urlStr);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- is = new BufferedInputStream(conn.getInputStream());
- is.mark(is.available());
-
- Options opts = new Options();
- opts.inJustDecodeBounds = true;
- Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts);
-
-
- ImageSize imageViewSize = ImageSizeUtil.getImageViewSize(imageview);
- opts.inSampleSize = ImageSizeUtil.caculateInSampleSize(opts,
- imageViewSize.width, imageViewSize.height);
-
- opts.inJustDecodeBounds = false;
- is.reset();
- bitmap = BitmapFactory.decodeStream(is, null, opts);
-
- conn.disconnect();
- return bitmap;
-
- } catch (Exception e)
- {
- e.printStackTrace();
- } finally
- {
- try
- {
- if (is != null)
- is.close();
- } catch (IOException e)
- {
- }
-
- try
- {
- if (fos != null)
- fos.close();
- } catch (IOException e)
- {
- }
- }
-
- return null;
-
- }
基本和本地壓縮差很少,也是兩次取樣,固然須要注意一點,咱們的is進行了包裝,以即可以進行reset();直接返回的is是不能使用兩次的。
到此,圖片壓縮說完了。
二、圖片加載框架的架構
咱們的圖片壓縮加載完了,那麼就應該放入咱們的LruCache,而後設置到咱們的ImageView上。
好了,接下來咱們來講說咱們的這個框架的架構;
一、單例,包含一個LruCache用於管理咱們的圖片;
二、任務隊列,咱們每來一次加載圖片的請求,咱們會封裝成Task存入咱們的TaskQueue;
三、包含一個後臺線程,這個線程在第一次初始化實例的時候啓動,而後會一直在後臺運行;任務呢?還記得咱們有個任務隊列麼,有隊列存任務,得有人幹活呀;因此,當每來一次加載圖片請求的時候,咱們同時發一個消息到後臺線程,後臺線程去使用線程池去TaskQueue去取一個任務執行;
四、調度策略;3中說了,後臺線程去TaskQueue去取一個任務,這個任務不是隨便取的,有策略能夠選擇,一個是FIFO,一個是LIFO,我傾向於後者。
好了,基本就這些結構,接下來看咱們具體的實現。
三、具體的實現
一、構造方法
- public static ImageLoader getInstance(int threadCount, Type type)
- {
- if (mInstance == null)
- {
- synchronized (ImageLoader.class)
- {
- if (mInstance == null)
- {
- mInstance = new ImageLoader(threadCount, type);
- }
- }
- }
- return mInstance;
- }
這個就不用說了,重點看咱們的構造方法
在貼構造的時候,順便貼出全部的成員變量;
在構造中咱們調用init,init中能夠設置後臺加載圖片線程數量和加載策略;init中首先初始化後臺線程initBackThread(),能夠看到這個後臺線程,其實是個Looper最終在那不斷的loop,咱們還初始化了一個mPoolThreadHandler用於發送消息到此線程;
接下來就是初始化mLruCache , mThreadPool ,mTaskQueue 等;
二、loadImage
構造完成之後,固然是使用了,用戶調用loadImage傳入(final String path, final ImageView imageView,final boolean isFromNet)就能夠完成本地或者網絡圖片的加載。
-
-
-
-
-
-
- public void loadImage(final String path, final ImageView imageView,
- final boolean isFromNet)
- {
- imageView.setTag(path);
- if (mUIHandler == null)
- {
- mUIHandler = new Handler()
- {
- public void handleMessage(Message msg)
- {
-
- ImgBeanHolder holder = (ImgBeanHolder) msg.obj;
- Bitmap bm = holder.bitmap;
- ImageView imageview = holder.imageView;
- String path = holder.path;
-
- if (imageview.getTag().toString().equals(path))
- {
- imageview.setImageBitmap(bm);
- }
- };
- };
- }
-
-
- Bitmap bm = getBitmapFromLruCache(path);
-
- if (bm != null)
- {
- refreashBitmap(path, imageView, bm);
- } else
- {
- addTask(buildTask(path, imageView, isFromNet));
- }
-
- }
首先咱們爲imageview.setTag;而後初始化一個mUIHandler,不用猜,這個mUIHandler用戶更新咱們的imageview,由於這個方法確定是主線程調用的。
而後調用:getBitmapFromLruCache(path);根據path在緩存中獲取bitmap;若是找到那麼直接去設置咱們的圖片;
- private void refreashBitmap(final String path, final ImageView imageView,
- Bitmap bm)
- {
- Message message = Message.obtain();
- ImgBeanHolder holder = new ImgBeanHolder();
- holder.bitmap = bm;
- holder.path = path;
- holder.imageView = imageView;
- message.obj = holder;
- mUIHandler.sendMessage(message);
- }
能夠看到,若是找到圖片,則直接使用UIHandler去發送一個消息,固然了攜帶了一些必要的參數,而後UIHandler的handleMessage中完成圖片的設置;
handleMessage中拿到path,bitmap,imageview;記得必需要:
// 將path與getTag存儲路徑進行比較
if (imageview.getTag().toString().equals(path))
{
imageview.setImageBitmap(bm);
}
不然會形成圖片混亂。
若是沒找到,則經過buildTask去新建一個任務,在addTask到任務隊列。
buildTask就比較複雜了,由於還涉及到本地和網絡,因此咱們先看addTask代碼:
- private synchronized void addTask(Runnable runnable)
- {
- mTaskQueue.add(runnable);
-
- try
- {
- if (mPoolThreadHandler == null)
- mSemaphorePoolThreadHandler.acquire();
- } catch (InterruptedException e)
- {
- }
- mPoolThreadHandler.sendEmptyMessage(0x110);
- }
很簡單,就是runnable加入TaskQueue,與此同時使用mPoolThreadHandler(這個handler還記得麼,用於和咱們後臺線程交互。)去發送一個消息給後臺線程,叫它去取出一個任務執行;具體代碼:
- mPoolThreadHandler = new Handler()
- {
- @Override
- public void handleMessage(Message msg)
- {
-
- mThreadPool.execute(getTask());
直接使用mThreadPool線程池,而後使用getTask去取一個任務。
-
-
-
-
-
- private Runnable getTask()
- {
- if (mType == Type.FIFO)
- {
- return mTaskQueue.removeFirst();
- } else if (mType == Type.LIFO)
- {
- return mTaskQueue.removeLast();
- }
- return null;
- }
getTask代碼也比較簡單,就是根據Type從任務隊列頭或者尾進行取任務。
如今你會不會好奇,任務裏面到底什麼代碼?其實咱們也就剩最後一段代碼了buildTask
-
-
-
-
-
-
-
-
- private Runnable buildTask(final String path, final ImageView imageView,
- final boolean isFromNet)
- {
- return new Runnable()
- {
- @Override
- public void run()
- {
- Bitmap bm = null;
- if (isFromNet)
- {
- File file = getDiskCacheDir(imageView.getContext(),
- md5(path));
- if (file.exists())
- {
- Log.e(TAG, "find image :" + path + " in disk cache .");
- bm = loadImageFromLocal(file.getAbsolutePath(),
- imageView);
- } else
- {
- if (isDiskCacheEnable)
- {
- boolean downloadState = DownloadImgUtils
- .downloadImgByUrl(path, file);
- if (downloadState)
- {
- Log.e(TAG,
- "download image :" + path
- + " to disk cache . path is "
- + file.getAbsolutePath());
- bm = loadImageFromLocal(file.getAbsolutePath(),
- imageView);
- }
- } else
-
- {
- Log.e(TAG, "load image :" + path + " to memory.");
- bm = DownloadImgUtils.downloadImgByUrl(path,
- imageView);
- }
- }
- } else
- {
- bm = loadImageFromLocal(path, imageView);
- }
-
- addBitmapToLruCache(path, bm);
- refreashBitmap(path, imageView, bm);
- mSemaphoreThreadPool.release();
- }
-
-
- };
- }
-
- private Bitmap loadImageFromLocal(final String path,
- final ImageView imageView)
- {
- Bitmap bm;
-
-
-
- ImageSize imageSize = ImageSizeUtil.getImageViewSize(imageView);
-
- bm = decodeSampledBitmapFromPath(path, imageSize.width,
- imageSize.height);
- return bm;
- }
咱們新建任務,說明在內存中沒有找到緩存的bitmap;咱們的任務就是去根據path加載壓縮後的bitmap返回便可,而後加入LruCache,設置回調顯示。
首先咱們判斷是不是網絡任務?
若是是,首先去硬盤緩存中找一下,(硬盤中文件名爲:根據path生成的md5爲名稱)。
若是硬盤緩存中沒有,那麼去判斷是否開啓了硬盤緩存:
開啓了的話:下載圖片,使用loadImageFromLocal本地加載圖片的方式進行加載(壓縮的代碼前面已經詳細說過);
若是沒有開啓:則直接從網絡獲取(壓縮獲取的代碼,前面詳細說過);
若是不是網絡圖片:直接loadImageFromLocal本地加載圖片的方式進行加載
通過上面,就得到了bitmap;而後加入addBitmapToLruCache,refreashBitmap回調顯示圖片。
-
-
-
-
-
-
- protected void addBitmapToLruCache(String path, Bitmap bm)
- {
- if (getBitmapFromLruCache(path) == null)
- {
- if (bm != null)
- mLruCache.put(path, bm);
- }
- }
到此,咱們全部的代碼就分析完成了;
緩存的圖片位置:在SD卡的Android/data/項目packageName/cache中:

不過有些地方須要注意:就是在代碼中,你會看到一些信號量的身影:
第一個:mSemaphorePoolThreadHandler = new Semaphore(0); 用於控制咱們的mPoolThreadHandler的初始化完成,咱們在使用mPoolThreadHandler會進行判空,若是爲null,會經過mSemaphorePoolThreadHandler.acquire()進行阻塞;當mPoolThreadHandler初始化結束,咱們會調用.release();解除阻塞。
第二個:mSemaphoreThreadPool = new Semaphore(threadCount);這個信號量的數量和咱們加載圖片的線程個數一致;每取一個任務去執行,咱們會讓信號量減一;每完成一個任務,會讓信號量+1,再去取任務;目的是什麼呢?爲何當咱們的任務到來時,若是此時在沒有空閒線程,任務則一直添加到TaskQueue中,當線程完成任務,能夠根據策略去TaskQueue中去取任務,只有這樣,咱們的LIFO纔有意義。
到此,咱們的圖片加載框架就結束了,你能夠嘗試下加載本地,或者去加載網絡大量的圖片,拼一拼加載速度~~~
四、MainActivity
如今是使用的時刻~~
我在MainActivity中,我使用了Fragment,下面我貼下Fragment和佈局文件的代碼,具體的,你們本身看代碼:
- package com.example.demo_zhy_18_networkimageloader;
-
- import android.content.Context;
- import android.os.Bundle;
- import android.support.v4.app.Fragment;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.ArrayAdapter;
- import android.widget.GridView;
- import android.widget.ImageView;
-
- import com.zhy.utils.ImageLoader;
- import com.zhy.utils.ImageLoader.Type;
- import com.zhy.utils.Images;
-
- public class ListImgsFragment extends Fragment
- {
- private GridView mGridView;
- private String[] mUrlStrs = Images.imageThumbUrls;
- private ImageLoader mImageLoader;
-
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- mImageLoader = ImageLoader.getInstance(3, Type.LIFO);
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState)
- {
- View view = inflater.inflate(R.layout.fragment_list_imgs, container,
- false);
- mGridView = (GridView) view.findViewById(R.id.id_gridview);
- setUpAdapter();
- return view;
- }
-
- private void setUpAdapter()
- {
- if (getActivity() == null || mGridView == null)
- return;
-
- if (mUrlStrs != null)
- {
- mGridView.setAdapter(new ListImgItemAdaper(getActivity(), 0,
- mUrlStrs));
- } else
- {
- mGridView.setAdapter(null);
- }
-
- }
-
- private class ListImgItemAdaper extends ArrayAdapter<String>
- {
-
- public ListImgItemAdaper(Context context, int resource, String[] datas)
- {
- super(getActivity(), 0, datas);
- Log.e("TAG", "ListImgItemAdaper");
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent)
- {
- if (convertView == null)
- {
- convertView = getActivity().getLayoutInflater().inflate(
- R.layout.item_fragment_list_imgs, parent, false);
- }
- ImageView imageview = (ImageView) convertView
- .findViewById(R.id.id_img);
- imageview.setImageResource(R.drawable.pictures_no);
- mImageLoader.loadImage(getItem(position), imageview, true);
- return convertView;
- }
-
- }
-
- }
能夠看到咱們在getView中,使用mImageLoader.loadImage一行即完成了圖片的加載。
fragment_list_imgs.xml
- <GridView xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/id_gridview"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:horizontalSpacing="3dp"
- android:verticalSpacing="3dp"
- android:numColumns="3"
- >
-
- </GridView>
item_fragment_list_imgs.xml
- <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/id_img"
- android:layout_width="match_parent"
- android:layout_height="120dp"
- android:scaleType="centerCrop" >
-
- </ImageView>
好了,到此結束~~~有任何bug或者意見歡迎留言~
源碼點擊下載
----------------------------------------------------------------------------------------------------------
博主部分視頻已經上線,若是你不喜歡枯燥的文本,請猛戳(初錄,期待您的支持):
一、Android 自定義控件實戰 電商活動中的刮刮卡
二、Android自定義控件實戰 打造Android流式佈局和熱門標籤
三、Android智能機器人「小慕」的實現
四、高仿QQ5.0側滑
五、高仿微信5.2.1主界面及消息提醒