tag: android pic skill

date: 2016/07/09

title: picasso-强大的Android图片下载缓存库


【本文转载自:泡在网上的日子 参考:http://blog.csdn.net/xu_fu/article/details/17043231】

转载请联系作者!

picasso是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,缓存类

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

this.map = new LinkedHashMap<String, Bitmap>(0, 0.75f, true);

因为可能会涉及多线程,所以在存取的时候都会加锁。而且每次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,操作封装类

所有对图形的操作都会记录在这里,供之后图形的创建使用,如重新计算大小,旋转角度,也可以自定义变换,只需要实现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代表了一个具体的加载任务,主要用于图片加载后的结果回调,有两个抽象方法,completeerror,也就是当图片解析为bitmap后用户希望做什么。最简单的就是将bitmap设置给imageview,失败了就将错误通过回调通知到上层。

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();
}
}

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

BitmapHunter

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。

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执行。

【本文转载自:泡在网上的日子 参考:http://blog.csdn.net/xu_fu/article/details/17043231】

转载请联系作者!

picasso_强大的Android图片下载缓存库的更多相关文章

  1. 毕加索的艺术——Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选

    毕加索的艺术--Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选 官网: http://square.github.i ...

  2. picasso-强大的Android图片下载缓存库

    编辑推荐:稀土掘金,这是一个针对技术开发者的一个应用,你可以在掘金上获取最新最优质的技术干货,不仅仅是Android知识.前端.后端以至于产品和设计都有涉猎,想成为全栈工程师的朋友不要错过! pica ...

  3. android开源项目:图片下载缓存库picasso

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

  4. 如何使用picasso 对Android图片下载缓存

    相比较其他,picasso的图片缓存更加简单一些,他只需要一行代码就可以表述:导入相关jar包 Picasso.with(context).load("图片路径").into(Im ...

  5. Android 图片加载库Glide 实战(二),占位符,缓存,转换自签名高级实战

    http://blog.csdn.net/sk719887916/article/details/40073747 请尊重原创 : skay <Android 图片加载库Glide 实战(一), ...

  6. Android图片加载库的理解

    前言     这是“基础自测”系列的第三篇文章,以Android开发需要熟悉的20个技术点为切入点,本篇重点讲讲Android中的ImageLoader这个库的一些理解,在Android上最让人头疼是 ...

  7. fackbook的Fresco (FaceBook推出的Android图片加载库-Fresco)

    [Android开发经验]FaceBook推出的Android图片加载库-Fresco   欢迎关注ndroid-tech-frontier开源项目,定期翻译国外Android优质的技术.开源库.软件 ...

  8. FaceBook推出的Android图片加载库-Fresco

    FaceBook推出的Android图片加载库-Fresco 原文链接:Introducing Fresco: A new image library for Android 译者 : ZhaoKai ...

  9. Android图片下载以及缓存框架

    实际开发中进行图片下载以及缓存的框架 介绍一下开发中常见图片加载框架的使用和对比一下优缺点. 1.Picasso 框架 在Android中开发,常需要从远程获取图片并显示在客户端,当然我们可以使用原生 ...

随机推荐

  1. PHP android ios相互兼容的AES加密算法

    APP项目用户密码传输一直没有用HTTPS,考虑到用户的隐私暂时先用AES对密码加密,以后也可以用于手机端与服务端加密交互. PHP的免费版phpAES项目,手机端解码各种不对. 好不容易找了PHP ...

  2. WdatePicker.js 日期时间插件

    支持功能: 1.支持常规在input单击或获得焦点时调用,还支持使用其他的元素如:<img><div>等触发WdatePicker函数来调用弹出日期框 @1.input 调用: ...

  3. opencv数据结构总结

    OpenCV里面用到了很多图像相关的数据结构,熟练掌握它们是学习图像的基础. 1.IplImage IplImage IplImage IPL 图像头 typedef struct _IplImage ...

  4. 由Python的super()函数想到的

    python-super *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !im ...

  5. SQL语句操作大全

    SQL语句操作大全   本文分为以下六个部分: 基础部分 提升部分 技巧部分 数据开发–经典部分 SQL Server基本函数部分 常识部分 一.基础 1.说明:创建数据库CREATE DATABAS ...

  6. Oracle数据库基础知识_字符串操作相关2

    6.LPAD,RPAD 作用:左/右边的字符串填充一些特定的字符语法: LPAD(string , n, [pad_String])          string:可是字符或者参数          ...

  7. 完美世界-2015校园招聘-java服务器工程师-成都站

    给定一个整数,将该整数分解成多个2的幂次方相加的形式,每次都取最大的可以分解出来的2的幂次方 比如 65 64 1 1 1 2 2 package wanmanshijie; import java. ...

  8. 转:Java架构师与开发者提高效率的10个工具

    原文来自于:http://www.importnew.com/14624.html Java受到全球百万计开发者的追捧,已经演变为一门出色的编程语言.最终,这门语言随着技术的变化,不断的被改善以迎合变 ...

  9. python global 全局变量

    http://blog.csdn.net/mldxs/article/details/8559973 __author__ = 'dell' def func(): global x print 'x ...

  10. hibernate spring 事务配置

    <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx: ...