首页 > 其他分享 >picasso--不得不看的异步图片加载与缓存开源库

picasso--不得不看的异步图片加载与缓存开源库

时间:2023-08-04 16:02:19浏览次数:77  
标签:异步 -- new bitmap Bitmap context Picasso picasso null


是Square公司开源的一个Android图形缓存库,地址http://square.github.io/picasso/,可以实现图片下载和缓存功能。仅仅只需要一行代码就能完全实现图片的异步加载:


Picasso.        with        (context).load(        "http://i.imgur.com/DvpvklR.png"        ).into(imageView);



看起来非常独特,是吧。

    Picasso不仅实现了图片异步加载的功能,还解决了android中加载图片时需要解决的一些常见问题:

   1.在adapter中需要取消已经不在视野范围的ImageView图片资源的加载,否则会导致图片错位,Picasso已经解决了这个问题。

   2.使用复杂的图片压缩转换来尽可能的减少内存消耗

   3.自带内存和硬盘二级缓存功能

 特性以及示例代码:

        ADAPTER 中的下载:Adapter的重用会被自动检测到,Picasso会取消上次的加载


@Override public void getView(int position, View convertView, ViewGroup parent) {       


                 SquaredImageView view = (SquaredImageView) convertView;       


                 if        (view ==         null        ) {       


                 view =         new        SquaredImageView(context);       


                 }       


                 String url = getItem(position);       


                 Picasso.        with        (context).load(url).into(view);       


         }



   图片转换:转换图片以适应布局大小并减少内存占用


Picasso.        with        (context)       


                 .load(url)       


                 .resize(50, 50)       


                 .centerCrop()       


                 .into(imageView);



   你还可以自定义转换:


public class CropSquareTransformation implements Transformation {       


                 @Override public Bitmap transform(Bitmap source) {       


                 int size = Math.min(source.getWidth(), source.getHeight());       


                 int x = (source.getWidth() - size) / 2;       


                 int y = (source.getHeight() - size) / 2;       


                 Bitmap result = Bitmap.createBitmap(source, x, y, size, size);       


                 if        (result != source) {       


                 source.recycle();       


                 }       


                 return        result;       


                 }       


                 @Override public String key() {         return        "square()"        ; }       


         }



   将CropSquareTransformation 的对象传递给transform 方法即可。


   Place holders-空白或者错误占位图片:picasso提供了两种占位图片,未加载完成或者加载发生错误的时需要一张图片作为提示。


Picasso.        with        (context)       


                 .load(url)       


                 .placeholder(R.drawable.user_placeholder)       


                 .error(R.drawable.user_placeholder_error)       


         .into(imageView);



   如果加载发生错误会重复三次请求,三次都失败才会显示erro Place holder

   资源文件的加载:除了加载网络图片picasso还支持加载Resources, assets, files, content providers中的资源文件。


Picasso.        with        (context).load(R.drawable.landing_screen).into(imageView1);       


         Picasso.        with        (context).load(        new        File(...)).into(imageView2);




下面是picasso源码的解析(不看不影响使用)

Cache,缓存类


picasso--不得不看的异步图片加载与缓存开源库_缓存




Lrucacha,主要是get和set方法,存储的结构采用了LinkedHashMap,这种map内部实现了lru算法(Least Recently Used 近期最少使用算法)。


this        .map =         new        LinkedHashMap<String, Bitmap>(0, 0.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操作后都会判断当前缓存区是否已满,如果满了就清掉最少使用的图形。代码如下


private void trimToSize(int maxSize) {       


                 while        (        true        ) {       


                 String key;       


                 Bitmap value;       


                 synchronized (        this        ) {       


                 if        (size < 0 || (map.isEmpty() && size != 0)) {       


                 throw        new           IllegalStateException(getClass().getName()       


                 +         ".sizeOf() is reporting inconsistent results!"        );       


                 }       


                 


                 if        (size <= maxSize || map.isEmpty()) {       


                 break        ;       


                 }       


                 


                 Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator()       


                 .next();       


                 key = toEvict.getKey();       


                 value = toEvict.getValue();       


                 map.remove(key);       


                 size -= Utils.getBitmapBytes(value);       


                 evictionCount++;       


                 }       


                 }       


         }



Request,操作封装类


picasso--不得不看的异步图片加载与缓存开源库_缓存_02




所有对图形的操作都会记录在这里,供之后图形的创建使用,如重新计算大小,旋转角度,也可以自定义变换,只需要实现Transformation,一个bitmap转换的接口。


public interface Transformation {       


                 /**       


                 * Transform the source bitmap into a new bitmap. If you create a new bitmap instance, you must       


                 * call {@link android.graphics.Bitmap#recycle()} on {@code source}. You may return the original       


                 * if no transformation is required.       


                 */       


                 Bitmap transform(Bitmap source);       


                 


                 /**       


                 * Returns a unique key for the transformation, used for caching purposes. If the transformation       


                 * has parameters (e.g. size, scale factor, etc) then these should be part of the key.       


                 */       


                 String key();       


         }



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

Action


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


picasso--不得不看的异步图片加载与缓存开源库_加载_03



ImageViewAction实现了Action,在complete中将bitmap和imageview组成了一个PicassoDrawable,里面会实现淡出的动画效果。



@Override       


                 public void complete(Bitmap result, Picasso.LoadedFrom from) {       


                 if        (result ==         null        ) {       


                 throw        new           AssertionError(String.format(       


                 "Attempted to complete action with no result!\n%s"        ,         this        ));       


                 }       


                 


                 ImageView target =         this        .target.get();       


                 if        (target ==         null        ) {       


                 return        ;       


                 }       


                 


                 Context context = picasso.context;       


                 boolean debugging = picasso.debugging;       


                 PicassoDrawable.setBitmap(target, context, result, from, noFade,       


                 debugging);       


                 


                 if        (callback !=         null        ) {       


                 callback.onSuccess();       


                 }       


                 }



nter。

BitmapHunter


picasso--不得不看的异步图片加载与缓存开源库_缓存_04


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




@Override       


                 public void run() {       


                 try        {       


                 Thread.currentThread()       


                 .setName(Utils.THREAD_PREFIX + data.getName());       


                 


                 result = hunt();       


                 


                 if        (result ==         null        ) {       


                 dispatcher.dispatchFailed(        this        );       


                 }         else        {       


                 dispatcher.dispatchComplete(        this        );       


                 }       


                 }         catch        (IOException e) {       


                 exception = e;       


                 dispatcher.dispatchRetry(        this        );       


                 }         catch        (Exception e) {       


                 exception = e;       


                 dispatcher.dispatchFailed(        this        );       


                 } finally {       


                 Thread.currentThread().setName(Utils.THREAD_IDLE_NAME);       


                 }       


                 }       


                 


                 abstract Bitmap decode(Request data) throws IOException;       


                 


                 Bitmap hunt() throws IOException {       


                 Bitmap bitmap;       


                 


                 if        (!skipMemoryCache) {       


                 bitmap = cache.get(key);       


                 if        (bitmap !=         null        ) {       


                 stats.dispatchCacheHit();       


                 loadedFrom = MEMORY;       


                 return        bitmap;       


                 }       


                 }       


                 


                 bitmap = decode(data);       


                 


                 if        (bitmap !=         null        ) {       


                 stats.dispatchBitmapDecoded(bitmap);       


                 if        (data.needsTransformation() || exifRotation != 0) {       


                 synchronized (DECODE_LOCK) {       


                 if        (data.needsMatrixTransform() || exifRotation != 0) {       


                 bitmap = transformResult(data, bitmap, exifRotation);       


                 }       


                 if        (data.hasCustomTransformations()) {       


                 bitmap = applyCustomTransformations(       


                 data.transformations, bitmap);       


                 }       


                 }       


                 stats.dispatchBitmapTransformed(bitmap);       


                 }       


                 }       


                 


                 return        bitmap;       


                 }



可以看到,在decode生成原始bitmap,之后会做需要的转换transformResult和applyCustomTransformations。最后在将最终的结果传递到上层dispatcher.dispatchComplete(this)。


基本的组成元素有了,那这一切是怎么连接起来运行呢,答案是Dispatcher。


Dispatcher任务调度器


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


picasso--不得不看的异步图片加载与缓存开源库_缓存_05


Dispatcher内有一个HandlerThread,所有的请求都会通过这个thread转换,也就是请求也是异步的,这样应该是为了Ui线程更加流畅,同时保证请求的顺序,因为handler的消息队列。


外部调用的是dispatchXXX方法,然后通过handler将请求转换到对应的performXXX方法。


例如生成Action以后就会调用dispather的dispatchSubmit()来请求执行,


void dispatchSubmit(Action action) {       


                 handler.sendMessage(handler.obtainMessage(REQUEST_SUBMIT, action));       


                 }



handler接到消息后转换到performSubmit方法


void performSubmit(Action action) {       


                 BitmapHunter hunter = hunterMap.get(action.getKey());       


                 if        (hunter !=         null        ) {       


                 hunter.attach(action);       


                 return        ;       


                 }       


                 


                 if        (service.isShutdown()) {       


                 return        ;       


                 }       


                 


                 hunter = forRequest(context, action.getPicasso(),         this        , cache, stats,       


                 action, downloader);       


                 hunter.future = service.submit(hunter);       


                 hunterMap.put(action.getKey(), hunter);       


                 }


这里将通过action得到具体的BitmapHunder,然后交给ExecutorService执行。


下面是Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView)的过程,


public static Picasso         with        (Context context) {       


                 if        (singleton ==         null        ) {       


                 singleton =         new        Builder(context).build();       


                 }       


                 return        singleton;       


                 }       


                 


                 public Picasso build() {       


                 Context context =         this        .context;       


                 


                 if        (downloader ==         null        ) {       


                 downloader = Utils.createDefaultDownloader(context);       


                 }       


                 if        (cache ==         null        ) {       


                 cache =         new        LruCache(context);       


                 }       


                 if        (service ==         null        ) {       


                 service =         new        PicassoExecutorService();       


                 }       


                 if        (transformer ==         null        ) {       


                 transformer = RequestTransformer.IDENTITY;       


                 }       


                 


                 Stats stats =         new        Stats(cache);       


                 


                 Dispatcher dispatcher =         new        Dispatcher(context, service, HANDLER,       


                 downloader, cache, stats);       


                 


                 return        new           Picasso(context, dispatcher, cache, listener,       


                 transformer, stats, debugging);       


                 }


在Picasso.with()的时候会将执行所需的所有必备元素创建出来,如缓存cache、执行executorService、调度dispatch等,在load()时创建Request,在into()中创建action、bitmapHunter,并最终交给dispatcher执行。

标签:异步,--,new,bitmap,Bitmap,context,Picasso,picasso,null
From: https://blog.51cto.com/u_14523369/6963904

相关文章

  • 作者推荐 | 【底层服务/编程功底系列】「底层技术原理」史上最清晰的采用程序员的视角
    背景介绍现在,零拷贝功能在Linux下几乎家喻户晓,但仍有很多人对其了解有限。为了解开这个功能的神秘面纱,我决定撰写一篇关于深入探讨的文章。本文将从用户模式应用程序的角度出发,介绍零拷贝的概念,省略了内核级的技术细节。希望通过本篇文章,可以帮助大家能更好地理解这个有用功能。什......
  • 这是一份不完整的数据竞赛年鉴
     Datawhale调研 主题:关于竞赛选手的反馈摘要:2019年的数据竞赛年鉴主要关于竞赛梳理和竞赛干货分享,但少了选手的反馈,今年将首次加入选手的真实感受。上周在Datawhale竞赛社群进行了调研,目前已收到354份问卷反馈,感谢每一个贡献者。没有填写问卷的同学文末阅读原文可以直接填写,将有......
  • 视频融合平台视频汇聚平台LiteCVR接入国标平台播放失败反馈处理案例
    视频监控平台LiteCVR安装部署轻松,可拓展功能丰富,服务器支持多协议多类型设备接入,包括但不限于华为SDK、宇视SDK、萤石SDK、乐橙SDK,国标GB28181、RTMP、RTSP/Onvif、海康SDK、大华SDK、海康Ehome等平台。平台支持海量视频汇聚管理,可提供视频监控直播、云端录像、云存储、录像检索与......
  • 20W奖金+实习机会:阿里巴巴达摩院最新时间序列赛事来了!
     Datawhale赛事 赛事:2021“AIEarth”人工智能挑战赛2021“AIEarth”人工智能创新挑战赛,由阿里巴巴达摩院联合南京信息工程大学、国家气候中心、国家海洋环境预报中心、安徽省气象局共同创办。大赛以“AI助力精准气象和海洋预测”为主题,聚焦全球大气海洋研究前沿方向,推进人工智......
  • 2020年社招面试技巧总结!
     Datawhale干货 作者:小白泽,复旦大学,Datawhale成员最近刚跳槽刚结束,也拿到了几家一线大厂的核心的offer,总结一下经验希望能帮到其他同学。这里不介绍具体的面试问题,只介绍些方法论。1.自身情况简单介绍下自身情况:国内top3硕士(众所周知,top3共有九所高校),某二线互联网企业算法工......
  • 接口测试之文件上传
    在日常工作中,经常有上传文件功能的测试场景,因此,本文介绍两种主流编写上传文件接口测试脚本的方法。首先,要知道文件上传的一般原理:客户端根据文件路径读取文件内容,将文件内容转换成二进制文件流的格式传输给服务端,而服务端接受客户端传过来的二进制文件流以及文件名称等信......
  • promethous+granfa+mysql监控部署
    一、Prometheus源码安装和启动配置普罗米修斯下载网址:https://prometheus.io/download/监控集成器下载地址:http://www.coderdocument.com/docs/prometheus/v2.14/instrumenting/exporters_and_integrations.html1.实验环境IP 角色 系统172.16.11.7 Prometheus服务端 CentOS7......
  • Port XXX is already in use. xxxx..解决办法-gradio退出可用
    原因:端口被占用,程序启动后关闭但端口依然存在解决办法:手动杀死端口  1.安装工具(已经有的不需要安装,直接跳到第二步)yuminstallnet-tools-y命令介绍:yum:自动化简单化地管理rpm包的命令。install:安装net-tools:网络工具 2.安装完毕,执行查看端口命令: netstat-tpln......
  • dijkstra算法
    【USACO】热浪#include<bits/stdc++.h>usingnamespacestd;structnode{ intu,dist; node(int_u,int_dist) { u=_u; dist=_dist; }};structnode2{ intv,w; node2(int_v,int_w) { v=_v; w=_w; }};structcmp{ booloperator()(nodea,nod......
  • HTML | HTML排版标签
    标签名标签含义单/双标签h1~h6标题双p段落双div没有任何含义,用于整体布局(生活中的包装袋)。双h1最好写一个,h2~h6能适当多写。h1~h6不能互相嵌套,例如:h1标签中最好不要写h2标签了。p标签很特殊!它里面不能有:h1~h6、p、div标签(暂......