Android实现图片的高效批量加载

前言:图片的加载,图片的处理,是Android开发程序员在开发中经常遇到的问题,比如,图片的压缩,图片批量的网络获取等。但是往往处理不当,就会报oom,那么如何解决这一类问题了,在分析了弘扬大牛的图片加载后,我觉得收益匪浅,下面,我就借花献佛,实现高效,批量,同时又避免出现oom,实现高效imageload。

分析:

不管是从网络还是本地的图片,加载都需要进行压缩,然后显示:用户要你压缩显示,会给我们什么?一个imageview,一个path,我们的职责就是压缩完成后显示上去。

废话不多说,直接分析上代码了:

1、本地图片的压缩

a、获得imageview想要显示的大小

想要压缩,我们第一步应该是获得imageview想要显示的大小,没大小肯定没办法压缩?

那么如何获得imageview想要显示的大小呢?

[java]   view plain  copy
  1. /** 
  2.      * 根据ImageView获适当的压缩的宽和高 
  3.      *  
  4.      * @param imageView 
  5.      * @return 
  6.      */  
  7.     public static ImageSize getImageViewSize(ImageView imageView)  
  8.     {  
  9.   
  10.         ImageSize imageSize = new ImageSize();  
  11.         DisplayMetrics displayMetrics = imageView.getContext().getResources()  
  12.                 .getDisplayMetrics();  
  13.   
  14.         LayoutParams lp = imageView.getLayoutParams();  
  15.   
  16.         int width = imageView.getWidth();// 获取imageview的实际宽度  
  17.         if (width <= 0)  
  18.         {  
  19.             width = lp.width;// 获取imageview在layout中声明的宽度  
  20.         }  
  21.         if (width <= 0)  
  22.         {  
  23.             // width = imageView.getMaxWidth();// 检查最大值  
  24.             width = getImageViewFieldValue(imageView, "mMaxWidth");  
  25.         }  
  26.         if (width <= 0)  
  27.         {  
  28.             width = displayMetrics.widthPixels;  
  29.         }  
  30.   
  31.         int height = imageView.getHeight();// 获取imageview的实际高度  
  32.         if (height <= 0)  
  33.         {  
  34.             height = lp.height;// 获取imageview在layout中声明的宽度  
  35.         }  
  36.         if (height <= 0)  
  37.         {  
  38.             height = getImageViewFieldValue(imageView, "mMaxHeight");// 检查最大值  
  39.         }  
  40.         if (height <= 0)  
  41.         {  
  42.             height = displayMetrics.heightPixels;  
  43.         }  
  44.         imageSize.width = width;  
  45.         imageSize.height = height;  
  46.   
  47.         return imageSize;  
  48.     }  
  49.   
  50.     public static class ImageSize  
  51.     {  
  52.         int width;  
  53.         int height;  
  54.     }

可以看到,我们拿到imageview以后:

首先企图通过getWidth获取显示的宽;有些时候,这个getWidth返回的是0;

那么我们再去看看它有没有在布局文件中书写宽;

如果布局文件中也没有精确值,那么我们再去看看它有没有设置最大值;

如果最大值也没设置,那么我们只有拿出我们的终极方案,使用我们的屏幕宽度;

总之,不能让它任性,我们一定要拿到一个合适的显示值。

可以看到这里或者最大宽度,我们用的反射,而不是getMaxWidth();维萨呢,因为getMaxWidth竟然要API 16,我也是醉了;为了兼容性,我们采用反射的方案。反射的代码就不贴了。

b、设置合适的inSampleSize

我们获得想要显示的大小,为了什么,还不是为了和图片的真正的宽高做比较,拿到一个合适的inSampleSize,去对图片进行压缩么。

那么首先应该是拿到图片的宽和高:

  1. // 获得图片的宽和高,并不把图片加载到内存中,把高和宽保存在我们的options里面:
  2.         BitmapFactory.Options options = new BitmapFactory.Options();  
  3.         options.inJustDecodeBounds = true;  
  4.         BitmapFactory.decodeFile(path, options);  

然后我们就可以happy的去计算inSampleSize了:

  1. /** 
  2.      * 根据需求的宽和高以及图片实际的宽和高计算SampleSize 
  3.      *  
  4.      * @param options 
  5.      * @param width 
  6.      * @param height 
  7.      * @return 
  8.      */  
  9.     public static int caculateInSampleSize(Options options, int reqWidth,  
  10.             int reqHeight)  
  11.     {  
  12.         int width = options.outWidth;  
  13.         int height = options.outHeight;  
  14.   
  15.         int inSampleSize = 1;  
  16.   
  17.         if (width > reqWidth || height > reqHeight)  
  18.         {  
  19.             int widthRadio = Math.round(width * 1.0f / reqWidth);  
  20.             int heightRadio = Math.round(height * 1.0f / reqHeight);  
  21.   
  22.             inSampleSize = Math.max(widthRadio, heightRadio);  
  23.         }  
  24.   
  25.         return inSampleSize;  
  26.     }  
options里面存了实际的宽和高;reqWidth和reqHeight就是我们之前得到的想要显示的大小;经过比较,得到一个合适的inSampleSize;

有了inSampleSize:

  1. options.inSampleSize = ImageSizeUtil.caculateInSampleSize(options,  
  2.                 width, height);  
  3.   
  4.         // 使用获得到的InSampleSize再次解析图片  
  5.         options.inJustDecodeBounds = false;  
  6.         Bitmap bitmap = BitmapFactory.decodeFile(path, options);  
  7.         return bitmap;  

2、网络图片的压缩

a、直接下载存到sd卡,然后采用本地的压缩方案。这种方式当前是在硬盘缓存开启的情况下,如果没有开启呢?

b、使用BitmapFactory.decodeStream(is, null, opts);

  1. /** 
  2.      * 根据url下载图片在指定的文件 
  3.      *  
  4.      * @param urlStr 
  5.      * @param file 
  6.      * @return 
  7.      */  
  8.     public static Bitmap downloadImgByUrl(String urlStr, ImageView imageview)  
  9.     {  
  10.         FileOutputStream fos = null;  
  11.         InputStream is = null;  
  12.         try  
  13.         {  
  14.             URL url = new URL(urlStr);  
  15.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  16.             is = new BufferedInputStream(conn.getInputStream());  
  17.             is.mark(is.available());  
  18.               
  19.             Options opts = new Options();  
  20.             opts.inJustDecodeBounds = true;  
  21.             Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts);  
  22.               
  23.             //获取imageview想要显示的宽和高  
  24.             ImageSize imageViewSize = ImageSizeUtil.getImageViewSize(imageview);  
  25.             opts.inSampleSize = ImageSizeUtil.caculateInSampleSize(opts,  
  26.                     imageViewSize.width, imageViewSize.height);  
  27.               
  28.             opts.inJustDecodeBounds = false;  
  29.             is.reset();  
  30.             bitmap = BitmapFactory.decodeStream(is, null, opts);  
  31.   
  32.             conn.disconnect();  
  33.             return bitmap;  
  34.   
  35.         } catch (Exception e)  
  36.         {  
  37.             e.printStackTrace();  
  38.         } finally  
  39.         {  
  40.             try  
  41.             {  
  42.                 if (is != null)  
  43.                     is.close();  
  44.             } catch (IOException e)  
  45.             {  
  46.             }  
  47.   
  48.             try  
  49.             {  
  50.                 if (fos != null)  
  51.                     fos.close();  
  52.             } catch (IOException e)  
  53.             {  
  54.             }  
  55.         }  
  56.   
  57.         return null;  
  58.   
  59.     }  

注意本地加载和网络加载的区别:

基本和本地压缩差不多,也是两次取样,当然需要注意一点,我们的is进行了包装,以便可以进行reset();直接返回的is是不能使用两次的。



3,图片加载框架的架构设计分析

我们的图片压缩加载完了,那么就应该放入我们的LruCache,然后设置到我们的ImageView上。

1、单例,包含一个LruCache用于管理我们的图片;

2、任务队列,我们每来一次加载图片的请求,我们会封装成Task存入我们的TaskQueue;

3、包含一个后台线程,这个线程在第一次初始化实例的时候启动,然后会一直在后台运行;任务呢?还记得我们有个任务队列么,有队列存任务,得有人干活呀;所以,当每来一次加载图片请求的时候,我们同时发一个消息到后台线程,后台线程去使用线程池去TaskQueue去取一个任务执行;

4、调度策略;3中说了,后台线程去TaskQueue去取一个任务,这个任务不是随便取的,有策略可以选择,一个是FIFO,一个是LIFO,我倾向于后者。

好了,基本就这些结构,接下来看我们具体的实现。



4,具体的实现

  1. public static ImageLoader getInstance(int threadCount, Type type)  
  2.     {  
  3.         if (mInstance == null)  
  4.         {  
  5.             synchronized (ImageLoader.class)  
  6.             {  
  7.                 if (mInstance == null)  
  8.                 {  
  9.                     mInstance = new ImageLoader(threadCount, type);  
  10.                 }  
  11.             }  
  12.         }  
  13.         return mInstance;  
  14.     }  


构造方法

  1. /** 
  2.  * 图片加载类 
  3.  *  
  4.  * @author zhy 
  5.  *  
  6.  */  
  7. public class ImageLoader  
  8. {  
  9.     private static ImageLoader mInstance;  
  10.   
  11.     /** 
  12.      * 图片缓存的核心对象 
  13.      */  
  14.     private LruCache<String, Bitmap> mLruCache;  
  15.     /** 
  16.      * 线程池 
  17.      */  
  18.     private ExecutorService mThreadPool;  
  19.     private static final int DEAFULT_THREAD_COUNT = 1;  
  20.     /** 
  21.      * 队列的调度方式 
  22.      */  
  23.     private Type mType = Type.LIFO;  
  24.     /** 
  25.      * 任务队列 
  26.      */  
  27.     private LinkedList<Runnable> mTaskQueue;  
  28.     /** 
  29.      * 后台轮询线程 
  30.      */  
  31.     private Thread mPoolThread;  
  32.     private Handler mPoolThreadHandler;  
  33.     /** 
  34.      * UI线程中的Handler 
  35.      */  
  36.     private Handler mUIHandler;  
  37.   
  38.     private Semaphore mSemaphorePoolThreadHandler = new Semaphore(0);  
  39.     private Semaphore mSemaphoreThreadPool;  
  40.   
  41.     private boolean isDiskCacheEnable = true;  
  42.   
  43.     private static final String TAG = "ImageLoader";  
  44.   
  45.     public enum Type  
  46.     {  
  47.         FIFO, LIFO;  
  48.     }  
  49.   
  50.     private ImageLoader(int threadCount, Type type)  
  51.     {  
  52.         init(threadCount, type);  
  53.     }  
  54.   
  55.     /** 
  56.      * 初始化 
  57.      *  
  58.      * @param threadCount 
  59.      * @param type 
  60.      */  
  61.     private void init(int threadCount, Type type)  
  62.     {  
  63.         initBackThread();  
  64.   
  65.         // 获取我们应用的最大可用内存  
  66.         int maxMemory = (int) Runtime.getRuntime().maxMemory();  
  67.         int cacheMemory = maxMemory / 8;  
  68.         mLruCache = new LruCache<String, Bitmap>(cacheMemory)  
  69.         {  
  70.             @Override  
  71.             protected int sizeOf(String key, Bitmap value)  
  72.             {  
  73.                 return value.getRowBytes() * value.getHeight();  
  74.             }  
  75.   
  76.         };  
  77.   
  78.         // 创建线程池  
  79.         mThreadPool = Executors.newFixedThreadPool(threadCount);  
  80.         mTaskQueue = new LinkedList<Runnable>();  
  81.         mType = type;  
  82.         mSemaphoreThreadPool = new Semaphore(threadCount);  
  83.     }  
  84.   
  85.     /** 
  86.      * 初始化后台轮询线程 
  87.      */  
  88.     private void initBackThread()  
  89.     {  
  90.         // 后台轮询线程  
  91.         mPoolThread = new Thread()  
  92.         {  
  93.             @Override  
  94.             public void run()  
  95.             {  
  96.                 Looper.prepare();  
  97.                 mPoolThreadHandler = new Handler()  
  98.                 {  
  99.                     @Override  
  100.                     public void handleMessage(Message msg)  
  101.                     {  
  102.                         // 线程池去取出一个任务进行执行  
  103.                         mThreadPool.execute(getTask());  
  104.                         try  
  105.                         {  
  106.                             mSemaphoreThreadPool.acquire();  
  107.                         } catch (InterruptedException e)  
  108.                         {  
  109.                         }  
  110.                     }  
  111.                 };  
  112.                 // 释放一个信号量  
  113.                 mSemaphorePoolThreadHandler.release();  
  114.                 Looper.loop();  
  115.             };  
  116.         };  
  117.   
  118.         mPoolThread.start();  
  119.     }  


在贴构造的时候,顺便贴出所有的成员变量;

在构造中我们调用init,init中可以设置后台加载图片线程数量和加载策略;init中首先初始化后台线程initBackThread(),可以看到这个后台线程,实际上是个Looper最终在那不断的loop,我们还初始化了一个mPoolThreadHandler用于发送消息到此线程;

接下来就是初始化mLruCache  , mThreadPool ,mTaskQueue 等;


loadImage

构造完成以后,当然是使用了,用户调用loadImage传入(final String path, final ImageView imageView,final boolean isFromNet)就可以完成本地或者网络图片的加载。

  1. /** 
  2.      * 根据path为imageview设置图片 
  3.      *  
  4.      * @param path 
  5.      * @param imageView 
  6.      */  
  7.     public void loadImage(final String path, final ImageView imageView,  
  8.             final boolean isFromNet)  
  9.     {  
  10.         imageView.setTag(path);  
  11.         if (mUIHandler == null)  
  12.         {  
  13.             mUIHandler = new Handler()  
  14.             {  
  15.                 public void handleMessage(Message msg)  
  16.                 {  
  17.                     // 获取得到图片,为imageview回调设置图片  
  18.                     ImgBeanHolder holder = (ImgBeanHolder) msg.obj;  
  19.                     Bitmap bm = holder.bitmap;  
  20.                     ImageView imageview = holder.imageView;  
  21.                     String path = holder.path;  
  22.                     // 将path与getTag存储路径进行比较  
  23.                     if (imageview.getTag().toString().equals(path))  
  24.                     {  
  25.                         imageview.setImageBitmap(bm);  
  26.                     }  
  27.                 };  
  28.             };  
  29.         }  
  30.   
  31.         // 根据path在缓存中获取bitmap  
  32.         Bitmap bm = getBitmapFromLruCache(path);  
  33.   
  34.         if (bm != null)  
  35.         {  
  36.             refreashBitmap(path, imageView, bm);  
  37.         } else  
  38.         {  
  39.             addTask(buildTask(path, imageView, isFromNet));  
  40.         }  
  41.  

首先我们为imageview.setTag;然后初始化一个mUIHandler,不用猜,这个mUIHandler用户更新我们的imageview,因为这个方法肯定是主线程调用的。

然后调用:getBitmapFromLruCache(path);根据path在缓存中获取bitmap;如果找到那么直接去设置我们的图片;


  1. private void refreashBitmap(final String path, final ImageView imageView,  
  2.             Bitmap bm)  
  3.     {  
  4.         Message message = Message.obtain();  
  5.         ImgBeanHolder holder = new ImgBeanHolder();  
  6.         holder.bitmap = bm;  
  7.         holder.path = path;  
  8.         holder.imageView = imageView;  
  9.         message.obj = holder;  
  10.         mUIHandler.sendMessage(message);  
  11.     }  


可以看到,如果找到图片,则直接使用UIHandler去发送一个消息,当然了携带了一些必要的参数,然后UIHandler的handleMessage中完成图片的设置;

handleMessage中拿到path,bitmap,imageview;记得必须要:

// 将path与getTag存储路径进行比较
if (imageview.getTag().toString().equals(path))
{
imageview.setImageBitmap(bm);
}

否则会造成图片混乱。

如果没找到,则通过buildTask去新建一个任务,在addTask到任务队列。

buildTask就比较复杂了,因为还涉及到本地和网络,所以我们先看addTask代码:


  1. private synchronized void addTask(Runnable runnable)  
  2.     {  
  3.         mTaskQueue.add(runnable);  
  4.         // if(mPoolThreadHandler==null)wait();  
  5.         try  
  6.         {  
  7.             if (mPoolThreadHandler == null)  
  8.                 mSemaphorePoolThreadHandler.acquire();  
  9.         } catch (InterruptedException e)  
  10.         {  
  11.         }  
  12.         mPoolThreadHandler.sendEmptyMessage(0x110);  
  13.     }  


很简单,就是runnable加入TaskQueue,与此同时使用mPoolThreadHandler(这个handler还记得么,用于和我们后台线程交互。)去发送一个消息给后台线程,叫它去取出一个任务执行;具体代码:


  1. mPoolThreadHandler = new Handler()  
  2.                 {  
  3.                     @Override  
  4.                     public void handleMessage(Message msg)  
  5.                     {  
  6.                         // 线程池去取出一个任务进行执行  
  7.                         mThreadPool.execute(getTask());  


直接使用mThreadPool线程池,然后使用getTask去取一个任务。

  1. /** 
  2.      * 从任务队列取出一个方法 
  3.      *  
  4.      * @return 
  5.      */  
  6.     private Runnable getTask()  
  7.     {  
  8.         if (mType == Type.FIFO)  
  9.         {  
  10.             return mTaskQueue.removeFirst();  
  11.         } else if (mType == Type.LIFO)  
  12.         {  
  13.             return mTaskQueue.removeLast();  
  14.         }  
  15.         return null;  
  16.     }  
getTask代码也比较简单,就是根据Type从任务队列头或者尾进行取任务。

现在你会不会好奇,任务里面到底什么代码?其实我们也就剩最后一段代码了buildTask

  1. /** 
  2.      * 根据传入的参数,新建一个任务 
  3.      *  
  4.      * @param path 
  5.      * @param imageView 
  6.      * @param isFromNet 
  7.      * @return 
  8.      */  
  9.     private Runnable buildTask(final String path, final ImageView imageView,  
  10.             final boolean isFromNet)  
  11.     {  
  12.         return new Runnable()  
  13.         {  
  14.             @Override  
  15.             public void run()  
  16.             {  
  17.                 Bitmap bm = null;  
  18.                 if (isFromNet)  
  19.                 {  
  20.                     File file = getDiskCacheDir(imageView.getContext(),  
  21.                             md5(path));  
  22.                     if (file.exists())// 如果在缓存文件中发现  
  23.                     {  
  24.                         Log.e(TAG, "find image :" + path + " in disk cache .");  
  25.                         bm = loadImageFromLocal(file.getAbsolutePath(),  
  26.                                 imageView);  
  27.                     } else  
  28.                     {  
  29.                         if (isDiskCacheEnable)// 检测是否开启硬盘缓存  
  30.                         {  
  31.                             boolean downloadState = DownloadImgUtils  
  32.                                     .downloadImgByUrl(path, file);  
  33.                             if (downloadState)// 如果下载成功  
  34.                             {  
  35.                                 Log.e(TAG,  
  36.                                         "download image :" + path  
  37.                                                 + " to disk cache . path is "  
  38.                                                 + file.getAbsolutePath());  
  39.                                 bm = loadImageFromLocal(file.getAbsolutePath(),  
  40.                                         imageView);  
  41.                             }  
  42.                         } else  
  43.                         // 直接从网络加载  
  44.                         {  
  45.                             Log.e(TAG, "load image :" + path + " to memory.");  
  46.                             bm = DownloadImgUtils.downloadImgByUrl(path,  
  47.                                     imageView);  
  48.                         }  
  49.                     }  
  50.                 } else  
  51.                 {  
  52.                     bm = loadImageFromLocal(path, imageView);  
  53.                 }  
  54.                 // 3、把图片加入到缓存  
  55.                 addBitmapToLruCache(path, bm);  
  56.                 refreashBitmap(path, imageView, bm);  
  57.                 mSemaphoreThreadPool.release();  
  58.             }  
  59.   
  60.               
  61.         };  
  62.     }  
  63.       
  64.     private Bitmap loadImageFromLocal(final String path,  
  65.             final ImageView imageView)  
  66.     {  
  67.         Bitmap bm;  
  68.         // 加载图片  
  69.         // 图片的压缩  
  70.         // 1、获得图片需要显示的大小  
  71.         ImageSize imageSize = ImageSizeUtil.getImageViewSize(imageView);  
  72.         // 2、压缩图片  
  73.         bm = decodeSampledBitmapFromPath(path, imageSize.width,  
  74.                 imageSize.height);  
  75.         return bm;  
  76.     }  


我们新建任务,说明在内存中没有找到缓存的bitmap;我们的任务就是去根据path加载压缩后的bitmap返回即可,然后加入LruCache,设置回调显示。



首先我们判断是否是网络任务?

如果是,首先去硬盘缓存中找一下,(硬盘中文件名为:根据path生成的md5为名称)。

如果硬盘缓存中没有,那么去判断是否开启了硬盘缓存:

开启了的话:下载图片,使用loadImageFromLocal本地加载图片的方式进行加载(压缩的代码前面已经详细说过);

         如果没有开启:则直接从网络获取(压缩获取的代码,前面详细说过);

如果不是网络图片:直接loadImageFromLocal本地加载图片的方式进行加载


经过上面,就获得了bitmap;然后加入addBitmapToLruCache,refreashBitmap回调显示图片。

  1. /** 
  2.      * 将图片加入LruCache 
  3.      *  
  4.      * @param path 
  5.      * @param bm 
  6.      */  
  7.     protected void addBitmapToLruCache(String path, Bitmap bm)  
  8.     {  
  9.         if (getBitmapFromLruCache(path) == null)  
  10.         {  
  11.             if (bm != null)  
  12.                 mLruCache.put(path, bm);  
  13.         }  
  14.     }  


到此,我们所有的代码就分析完成了;缓存的图片位置:在SD卡的Android/data/项目packageName/cache中:

注意事项:

第一个:mSemaphorePoolThreadHandler = new Semaphore(0); 用于控制我们的mPoolThreadHandler的初始化完成,我们在使用mPoolThreadHandler会进行判空,如果为null,会通过mSemaphorePoolThreadHandler.acquire()进行阻塞;当mPoolThreadHandler初始化结束,我们会调用.release();解除阻塞。

第二个:mSemaphoreThreadPool = new Semaphore(threadCount);这个信号量的数量和我们加载图片的线程个数一致;每取一个任务去执行,我们会让信号量减一;每完成一个任务,会让信号量+1,再去取任务;目的是什么呢?为什么当我们的任务到来时,如果此时在没有空闲线程,任务则一直添加到TaskQueue中,当线程完成任务,可以根据策略去TaskQueue中去取任务,只有这样,我们的LIFO才有意义。


调用方式:

在要使用批量加载的activity或者片段调用一下方法即可:

1:先实例化

private ImageLoader mImageLoader; 

 mImageLoader = ImageLoader.getInstance(3, Type.LIFO); 

2:找到要使用的imagevie

imageview.setImageResource(R.drawable.pictures_no);  //设置预加载

 mImageLoader.loadImage(getItem(position), imageview, true);  




  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值