picasso图片缓存框架

简介: picasso是Square公司开源的一个Android图形缓存库,地址http://square.github.io/picasso/,可以实现图片下载和缓存功能。 picasso使用简单,如下 [java] view plaincopyprint? Picasso.with(context).load("http://i.imgur.c

picasso是Square公司开源的一个Android图形缓存库,地址http://square.github.io/picasso/,可以实现图片下载和缓存功能。

picasso使用简单,如下

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);  

主要有以下一些特性:

  • 在adapter中回收和取消当前的下载;
  • 使用最少的内存完成复杂的图形转换操作;
  • 自动的内存和硬盘缓存;
  • 图形转换操作,如变换大小,旋转等,提供了接口来让用户可以自定义转换操作;
  • 加载载网络或本地资源;

代码分析

Cache,缓存类



Lrucacha,主要是get和set方法,存储的结构采用了LinkedHashMap,这种map内部实现了lru算法(Least Recently Used 近期最少使用算法)。
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. this.map = new LinkedHashMap<String, Bitmap>(00.75f, true);  

最后一个参数的解释:
true if the ordering should be done based on the last access (from least-recently accessed to most-recently accessed), and false if the ordering should be the order in which the entries were inserted.
因为可能会涉及多线程,所以在存取的时候都会加锁。而且每次set操作后都会判断当前缓存区是否已满,如果满了就清掉最少使用的图形。代码如下
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. private void trimToSize(int maxSize) {  
  2.         while (true) {  
  3.             String key;  
  4.             Bitmap value;  
  5.             synchronized (this) {  
  6.                 if (size < 0 || (map.isEmpty() && size != 0)) {  
  7.                     throw new IllegalStateException(getClass().getName()  
  8.                             + ".sizeOf() is reporting inconsistent results!");  
  9.                 }  
  10.   
  11.                 if (size <= maxSize || map.isEmpty()) {  
  12.                     break;  
  13.                 }  
  14.   
  15.                 Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator()  
  16.                         .next();  
  17.                 key = toEvict.getKey();  
  18.                 value = toEvict.getValue();  
  19.                 map.remove(key);  
  20.                 size -= Utils.getBitmapBytes(value);  
  21.                 evictionCount++;  
  22.             }  
  23.         }  
  24. }  

Request,操作封装类



所有对图形的操作都会记录在这里,供之后图形的创建使用,如重新计算大小,旋转角度,也可以自定义变换,只需要实现Transformation,一个bitmap转换的接口。
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public interface Transformation {  
  2.   /** 
  3.    * Transform the source bitmap into a new bitmap. If you create a new bitmap instance, you must 
  4.    * call {@link android.graphics.Bitmap#recycle()} on {@code source}. You may return the original 
  5.    * if no transformation is required. 
  6.    */  
  7.   Bitmap transform(Bitmap source);  
  8.   
  9.   /** 
  10.    * Returns a unique key for the transformation, used for caching purposes. If the transformation 
  11.    * has parameters (e.g. size, scale factor, etc) then these should be part of the key. 
  12.    */  
  13.   String key();  
  14. }  

当操作封装好以后,会将Request传到另一个结构中Action。

Action

Action代表了一个具体的加载任务,主要用于图片加载后的结果回调,有两个抽象方法,complete和error,也就是当图片解析为bitmap后用户希望做什么。最简单的就是将bitmap设置给imageview,失败了就将错误通过回调通知到上层。


ImageViewAction实现了Action,在complete中将bitmap和imageview组成了一个PicassoDrawable,里面会实现淡出的动画效果。
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2.     public void complete(Bitmap result, Picasso.LoadedFrom from) {  
  3.         if (result == null) {  
  4.             throw new AssertionError(String.format(  
  5.                     "Attempted to complete action with no result!\n%s"this));  
  6.         }  
  7.   
  8.         ImageView target = this.target.get();  
  9.         if (target == null) {  
  10.             return;  
  11.         }  
  12.   
  13.         Context context = picasso.context;  
  14.         boolean debugging = picasso.debugging;  
  15.         PicassoDrawable.setBitmap(target, context, result, from, noFade,  
  16.                 debugging);  
  17.   
  18.         if (callback != null) {  
  19.             callback.onSuccess();  
  20.         }  
  21.     }  

有了加载任务,具体的图片下载与解析是在哪里呢?这些都是耗时的操作,应该放在异步线程中进行,就是下面的BitmapHunter。

BitmapHunter


BitmapHunter是一个Runnable,其中有一个decode的抽象方法,用于子类实现不同类型资源的解析。

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2.     public void run() {  
  3.         try {  
  4.             Thread.currentThread()  
  5.                     .setName(Utils.THREAD_PREFIX + data.getName());  
  6.   
  7.             result = hunt();  
  8.   
  9.             if (result == null) {  
  10.                 dispatcher.dispatchFailed(this);  
  11.             } else {  
  12.                 dispatcher.dispatchComplete(this);  
  13.             }  
  14.         } catch (IOException e) {  
  15.             exception = e;  
  16.             dispatcher.dispatchRetry(this);  
  17.         } catch (Exception e) {  
  18.             exception = e;  
  19.             dispatcher.dispatchFailed(this);  
  20.         } finally {  
  21.             Thread.currentThread().setName(Utils.THREAD_IDLE_NAME);  
  22.         }  
  23.     }  
  24.   
  25.     abstract Bitmap decode(Request data) throws IOException;  
  26.   
  27.     Bitmap hunt() throws IOException {  
  28.         Bitmap bitmap;  
  29.   
  30.         if (!skipMemoryCache) {  
  31.             bitmap = cache.get(key);  
  32.             if (bitmap != null) {  
  33.                 stats.dispatchCacheHit();  
  34.                 loadedFrom = MEMORY;  
  35.                 return bitmap;  
  36.             }  
  37.         }  
  38.   
  39.         bitmap = decode(data);  
  40.   
  41.         if (bitmap != null) {  
  42.             stats.dispatchBitmapDecoded(bitmap);  
  43.             if (data.needsTransformation() || exifRotation != 0) {  
  44.                 synchronized (DECODE_LOCK) {  
  45.                     if (data.needsMatrixTransform() || exifRotation != 0) {  
  46.                         bitmap = transformResult(data, bitmap, exifRotation);  
  47.                     }  
  48.                     if (data.hasCustomTransformations()) {  
  49.                         bitmap = applyCustomTransformations(  
  50.                                 data.transformations, bitmap);  
  51.                     }  
  52.                 }  
  53.                 stats.dispatchBitmapTransformed(bitmap);  
  54.             }  
  55.         }  
  56.   
  57.         return bitmap;  
  58.     }  

可以看到,在decode生成原始bitmap,之后会做需要的转换transformResult和applyCustomTransformations。最后在将最终的结果传递到上层dispatcher.dispatchComplete(this)。
基本的组成元素有了,那这一切是怎么连接起来运行呢,答案是Dispatcher。

Dispatcher任务调度器

在bitmaphunter成功得到bitmap后,就是通过dispatcher将结果传递出去的,当然让bitmaphunter执行也要通过Dispatcher。

Dispatcher内有一个HandlerThread,所有的请求都会通过这个thread转换,也就是请求也是异步的,这样应该是为了Ui线程更加流畅,同时保证请求的顺序,因为handler的消息队列。
外部调用的是dispatchXXX方法,然后通过handler将请求转换到对应的performXXX方法。
例如生成Action以后就会调用dispather的dispatchSubmit()来请求执行,
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. void dispatchSubmit(Action action) {  
  2.         handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));  
  3.     }  

handler接到消息后转换到performSubmit方法
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. void performSubmit(Action action) {  
  2.         BitmapHunter hunter = hunterMap.get(action.getKey());  
  3.         if (hunter != null) {  
  4.             hunter.attach(action);  
  5.             return;  
  6.         }  
  7.   
  8.         if (service.isShutdown()) {  
  9.             return;  
  10.         }  
  11.   
  12.         hunter = forRequest(context, action.getPicasso(), this, cache, stats,  
  13.                 action, downloader);  
  14.         hunter.future = service.submit(hunter);  
  15.         hunterMap.put(action.getKey(), hunter);  
  16.     }  

这里将通过action得到具体的BitmapHunder,然后交给ExecutorService执行。
下面是Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView)的过程,
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public static Picasso with(Context context) {  
  2.         if (singleton == null) {  
  3.             singleton = new Builder(context).build();  
  4.         }  
  5.         return singleton;  
  6.     }  
  7.       
  8.     public Picasso build() {  
  9.             Context context = this.context;  
  10.   
  11.             if (downloader == null) {  
  12.                 downloader = Utils.createDefaultDownloader(context);  
  13.             }  
  14.             if (cache == null) {  
  15.                 cache = new LruCache(context);  
  16.             }  
  17.             if (service == null) {  
  18.                 service = new PicassoExecutorService();  
  19.             }  
  20.             if (transformer == null) {  
  21.                 transformer = RequestTransformer.IDENTITY;  
  22.             }  
  23.   
  24.             Stats stats = new Stats(cache);  
  25.   
  26.             Dispatcher dispatcher = new Dispatcher(context, service, HANDLER,  
  27.                     downloader, cache, stats);  
  28.   
  29.             return new Picasso(context, dispatcher, cache, listener,  
  30.                     transformer, stats, debugging);  
  31.         }  

在Picasso.with()的时候会将执行所需的所有必备元素创建出来,如缓存cache、执行executorService、调度dispatch等,在load()时创建Request,在into()中创建action、bitmapHunter,并最终交给dispatcher执行。
目录
相关文章
|
4月前
|
XML 缓存 Java
Android App开发之利用Glide实现图片的三级缓存Cache讲解及实战(附源码 超详细必看 简单易懂)
Android App开发之利用Glide实现图片的三级缓存Cache讲解及实战(附源码 超详细必看 简单易懂)
112 0
|
存储 缓存 监控
简单聊聊Glide的内存缓存
glide的内存缓存有两级:LruCache、ActiveResources 其中LruCache老生常谈了,这里就不细说了。 ActiveResources实际上内含一个HashMap,Map中value则是资源的弱引用。 那么这两级是如何工作的?
259 0
|
缓存
Picasso图片框架加载图片 使用及缓存问题
Picasso图片框架加载图片 使用及缓存问题
|
存储 缓存 Java
图片加载框架-Picasso最详细的使用指南
图片加载框架-Picasso最详细的使用指南
图片加载框架-Picasso最详细的使用指南
|
Web App开发 移动开发 前端开发
Picasso:开启大前端的未来
Picasso源自我们对大前端实践的重新思考,以简洁高效的架构达成高性能的页面渲染目标。在实践中,甚至可以把Native技术向Picasso技术的迁移当做一种性能优化手段;与此同时,Picasso在跨越小程序端和Web端方面的工作已经取得了突破性进展,有望在四端(Android、iOS、H5、微信小程序)统一大前端实践的基础之上,达成高性能大前端实践,同时配合Picasso布局DSL强表达能力和Picasso代码生成技术,可以进一步提升生产力。
1934 0
关于glide图片加载框架的实际使用要点
第一部分:先说用glide踩的坑。 最近在项目中,加载图片用的是glide框架,遇到坑的地方,在load(url),内的url不能丢了。比如: Glide.with(mContext)         .load("img2.3lian.com/2014/f6/173/d/55.jpg")         .into(ivOrderGoodsImg); 这样,图片无法显示,一般glide载入图片失败有几个原因,1:into()方法没有载入正确的ImageView控件,比如载入到TextView的实例化对象中;2:load()方法中的网址不正确。
1630 0
|
缓存 Android开发 设计模式
16.手写图片加载框架ImageLoader
概述 第三方开源的图片框架很多,这里自己去写一个的目的是通过这样一个写的过程,拓展自己对架构设计的理解,包括设计模式,线程,策略,缓存等等。另外大型的框架例如Glide,代码很完善,扩展性很高,但是阅读起来有难度,而实际上,这些框架底层实现原理都是类似的,所以通过构建一个简单框架的过程更加有助于对其原理的理解,算是为阅读复杂的第三方源码打下一个基础。
1082 0
|
缓存 Android开发
Glide缓存配置
Glide依赖 //这里用的是Android Studio3.0 implementation 'com.github.bumptech.glide:glide:4.
1588 0
|
Android开发 缓存 编解码
Android应用开发-图片加载库Glide
Glide Picasso和Glide之间的区别: Picasso 仅仅缓存了全尺寸的图像;然而 Glide 缓存了原始图像,全分辨率图像和另外小版本的图像。
903 0
|
缓存 API Java
Google图片加载库Glide的简单封装GlideUtils
Google图片加载库Glide的简单封装GlideUtils 因为项目里用的Glide的地方比较多,所有简单的封装了以下,其实也没什么,就是写了个工具类,但是还是要把基础说下 Glide的Github https://github.
1089 0