picasso-强大的Android图片下载缓存库
picasso是Square公司开源的一个Android图形缓存库,地址http://square.github.io/picasso/,可以实现图片下载和缓存功能。仅仅只需要一行代码就能完全实现图片的异步加载:
- Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Api看起来非常独特,是吧。

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,缓存类
- this.map = new LinkedHashMap<String, Bitmap>(0, 0.75f, true);
- 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,操作封装类
- 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
- @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();
- }
- }
有了加载任务,具体的图片下载与解析是在哪里呢?这些都是耗时的操作,应该放在异步线程中进行,就是下面的BitmapHunter。
BitmapHunter
- @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;
- }
Dispatcher任务调度器
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);
- }
- 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执行。
picasso-强大的Android图片下载缓存库的更多相关文章
- 毕加索的艺术——Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选
毕加索的艺术--Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选 官网: http://square.github.i ...
- picasso_强大的Android图片下载缓存库
tag: android pic skill date: 2016/07/09 title: picasso-强大的Android图片下载缓存库 [本文转载自:泡在网上的日子 参考:http://bl ...
- android开源项目:图片下载缓存库picasso
picasso是Square公司开源的一个Android图形缓存库,地址http://square.github.io/picasso/,可以实现图片下载和缓存功能. picasso有如下特性: 在a ...
- 如何使用picasso 对Android图片下载缓存
相比较其他,picasso的图片缓存更加简单一些,他只需要一行代码就可以表述:导入相关jar包 Picasso.with(context).load("图片路径").into(Im ...
- Android 图片加载库Glide 实战(二),占位符,缓存,转换自签名高级实战
http://blog.csdn.net/sk719887916/article/details/40073747 请尊重原创 : skay <Android 图片加载库Glide 实战(一), ...
- fackbook的Fresco (FaceBook推出的Android图片加载库-Fresco)
[Android开发经验]FaceBook推出的Android图片加载库-Fresco 欢迎关注ndroid-tech-frontier开源项目,定期翻译国外Android优质的技术.开源库.软件 ...
- FaceBook推出的Android图片加载库-Fresco
FaceBook推出的Android图片加载库-Fresco 原文链接:Introducing Fresco: A new image library for Android 译者 : ZhaoKai ...
- Android图片加载库的理解
前言 这是“基础自测”系列的第三篇文章,以Android开发需要熟悉的20个技术点为切入点,本篇重点讲讲Android中的ImageLoader这个库的一些理解,在Android上最让人头疼是 ...
- Android图片下载以及缓存框架
实际开发中进行图片下载以及缓存的框架 介绍一下开发中常见图片加载框架的使用和对比一下优缺点. 1.Picasso 框架 在Android中开发,常需要从远程获取图片并显示在客户端,当然我们可以使用原生 ...
随机推荐
- [troubleshoot][archlinux][bcache] 修改linux文件系统 / 分区方案 / 做混合硬盘 / 系统转生大!手!术!(调整底层架构,不!重!装!)
目标: 我要做的事情是:修改文件系统,硬盘分区方案,但是不重装系统,整个操作不被应用层感知. 背景: 我的笔记本 ThinkPad T450.8G内存 + 16GB SSD + 1TB HDD.预装w ...
- block(代码块)的介绍以及使用方法和变量之间的关系
http://blog.csdn.net/menxu_work/article/details/8762848 block(代码块)的介绍以及使用方法和变量之间的关系 block(代码块)的介绍以及使 ...
- css3渐变之linear-gradient与-webkit-linear-gradient写法异同
语法background: linear-gradient(direction, color-stop1, color-stop2, ...); 通常只需要linear-gradient,兼容性较好. ...
- 使用Android Studio进行单元测试
Android Studio默认支持Android单元测试,不需要像网上说的配置mainifest.xml或build.gradle. 创建单元测试文件夹 可以把单元测试文件夹放到你自己创建的文件夹中 ...
- Android-项目介绍
一个.net开发人员 在了解android项目只能凭自己的理解慢慢来了! 新建项目 右击 New-JAVA Application Project 傻瓜似的下一步骤填写每一步 文件介绍 Android ...
- JSP中的指令(Directive)
- Python基础二. 数据结构、控制流、运算符、真值测试
一.概述 数据结构上广义上有两种,单一类型和集合类型 单一类型,表示一种对象 集合类型,表示包含多种对象 Python 中的内建的数据类型有str.list.tuple.dict.set.number ...
- dubbo源码分析4-基于netty的dubbo协议的server
dubbo源码分析1-reference bean创建 dubbo源码分析2-reference bean发起服务方法调用 dubbo源码分析3-service bean的创建与发布 dubbo源码分 ...
- MC, MCMC, Gibbs采样 原理&实现(in R)
本文用讲一下指定分布的随机抽样方法:MC(Monte Carlo), MC(Markov Chain), MCMC(Markov Chain Monte Carlo)的基本原理,并用R语言实现了几个例 ...
- AngularJS语法格式小结
//创建一个最大的容器,"唯一的名字" []数组 var a=angular.module("abcd",[]); //控制器 a.controller(&qu ...