https://github.com/nostra13/Android-Universal-Image-Loader

ImageLoader作用

1.多线程下载图片,图片可以来源于网络,文件系统,项目文件夹assets中以及drawable中
2.支持图片的内存缓存,文件系统缓存或者SD卡缓存
3.支持图片下载过程的监听
4.根据控件(ImageView)的大小对Bitmap进行裁剪,减少Bitmap占用过多的内存


加载第三方库

Gradle代码
‘com.nostra13.universalimageloader:universal-image-loader:1.9.4’

权限

1
2
<uses-permission android:name="android.permission.INTERNET" />  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

ImageLoader加载的类型

1
2
3
4
5
6
7
"http://site.com/image.png"// from Web  
"file:///mnt/sdcard/image.png" // from SD card
"file:///mnt/sdcard/video.mp4" // from SD card (video thumbnail)
"content://media/external/images/media/13" // from content provider
"content://media/external/video/media/13" // from content provider (video thumbnail)
"assets://image.png" // from assets
"drawable://" + R.drawable.img // from drawables [用imageView.setImageResource(drawable)来代替]

ImageLoader的加载、显示配置:

加载Image时的配置(ImageLoaderConfiguration)

自定义配置 - 通过new ImageLoaderConfiguration.Builder().builder()方法进行实例化。
默认配置 - 通过ImageLoaderConfiguration 的createDefault进行实例化。

  • 默认配置
1
2
3
4
5
6
7
8
9
File diskCache = StorageUtils.getOwnCacheDirectory(context, "BNJ_IMAGE_CACHE/");  
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.diskCache(new UnlimitedDiscCache(diskCache)) // 设置缓存路径
.memoryCacheSize(2 * 1024) // 设置缓存的最大字节
.diskCacheFileNameGenerator(new Md5FileNameGenerator()) // 加密
.denyCacheImageMultipleSizesInMemory() // 禁止缓存显示不同大小的同一张图片
.memoryCacheExtraOptions(800, 760) // 保存每个缓存图片的最大长和宽
.diskCacheFileCount(100) //缓存的File数量
.build();

使用
通过ImageLoader的getInstance().init()方法传入上述options对象.

显示Image时的配置(DisplayImageOptions)

自定义配置 - 通过new DisplayImageOptions.Builder().builder()方法实例化对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
DisplayImageOptions options = new DisplayImageOptions.Builder()  
.showImageOnLoading(R.drawable.ic_stub) // 设置加载时的图片 (使用loadImage方法加载时无效)
.showImageForEmptyUri(R.drawable.ic_empty) // resource or drawable
.showImageOnFail(R.drawable.ic_error) // 设置加载失败的图片
.cacheInMemory(true) //设置使用内存缓存
.cacheOnDisk(true) //使用文件缓存
.displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
.bitmapConfig(Bitmap.Config.RGB_565) //减少内存消耗
.delayBeforeLoading(100) //设置下载图片前的延时
.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.considerExifParams(false) //是否考虑JPEG图像EXIF参数(旋转,翻转)
.build(); ImageSize size= new ImageSize(300,300);(大小可以通过创建ImageSize对象设置) 上述图片显示displayer
//显示圆角 RoundedBitmapDisplayer
//淡入显示 FadeInBitmapDisplayer

加载图片的方法

loadImage跟displayImage

A.ImageLoader.getInstance().loadImage(uri地址,图片大小,上述配置,监听器,进度监听器);
B.ImageLoader.getinstance().displayImage(uri地址,控件,上述配置,监听器,进度监听器);


区别
A方法可以设置图片大小,即自定义下载图片的大小
B方法会根据控件大小及ImageScaleType来裁剪图片
常用displayImage方法


监听器有两种
SimpleImageLoadingListener(简单的监听器)
ImageLoadingListener (该监听器能实现 加载图片取消时,失败时的方法)
ImageLoadingProgressListener
最后在监听器的onLoadingComplete方法里,设置图片显示即可


进阶
listView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));
第一个参数是imageLoader,第二个参数是滑动时是否加载图片,第三个参数是猛的滑动时是否加载图片

OOM问题

如果使用了ImageLoader出现OutOfMemoryError的话,那么可以通过下列方法解决
关闭memory的cache。

减少线程池的大小
用Bitmap.Config.RGB565代替ARGB8888
使用.imageScaleType(ImageScaleType.EXACTLY 或ImageScaleType.IN_SAMPLE_INT)
使用.diskCacheExtraOption(480, 320, null)

获取缓存文件

1
2
DiskCache diskCache = ImageLoader.getInstance().getDiskCache();
File cacheFile = DiskCacheUtils.findInCache(imgpath, diskCache);

ImageView ScaleType

ImageLoader的使用及封装

使用

1.全局初始化ImageLoader,配置ImageLoader的参数(ImageLoaderConfiguration)
2.配置图片加载的参数(DisplayImageOptions)
3.创建ImageLoader的对象,调用displayImage方法

封装

1.利用单例模式创建ImageLoaderTool的对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class ImageLoaderTool{

	private static ImageLoader imageLoader;//用于全局初始化
private static ImageLoaderConfiguration configuration;//配置ImageLoader的参数 private static class Holder{ //单例模式
private static final ImageLoaderTool imageLoaderTool = new ImageLoaderTool();
} public static ImageLoaderTool getInstance(){
if(configuration==null || imageLoader==null){
throw new RunTimeException ("Must be call the method InitImageLoader(Context context) in Application");
}
return Holder.imageLoaderTool;
}
}

2.初始化ImageLoaderConfiguration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void initImageLoader(Context context) {
File diskCache = StorageUtils.getOwnCacheDirectory(context, "TJD_NBA/");
if (configuration == null) {
configuration = new ImageLoaderConfiguration.Builder(context)
.diskCache(new UnlimitedDiskCache(diskCache))
.diskCacheFileNameGenerator(new Md5FileNameGenerator()) //md5加密
.memoryCacheSize(1024 * 2)//缓存最大字节
.memoryCache(new LruMemoryCache(5 * 1024 * 1024))//解决缓存listview滑动后显示默认图
.memoryCacheExtraOptions(800, 760)// 保存每个缓存图片的最大长和宽
.diskCacheFileCount(100) //缓存的File数量
.build();
}
if (imageLoader == null) {
imageLoader = ImageLoader.getInstance();
imageLoader.init(configuration);
}
}

3.封装DisplayImage方法

1
2
3
4
5
6
7
8
9
/**
* 加载drawable图片,不能加载系统的drawable 即android:drawable
*
* @param resid
* @param imageView
*/
public void loadImageFromDrawable(int resid, ImageView imageView) {
imageLoader.displayImage(DRAWABLE_PREFIX + resid, imageView);
}

示例 - 封装ImageLoader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* ImageLoader的封装。单例模式
* 1. "http://site.com/image.png" // from Web
* 2. "file:///mnt/sdcard/image.png" // from SD card
* 3. "file:///mnt/sdcard/video.mp4" // from SD card (video thumbnail)
* 4. "content://media/external/images/media/13" // from content provider
* 5. "content://media/external/video/media/13" // from content provider (video thumbnail)
* 6. "assets://image.png" // from assets
* 7. "drawable://" + R.drawable.img // from drawables (non-9patch images)[用imageView.setImageResource(drawable)来代替]
*/
public class ImageLoaderTool { private static ImageLoader imageLoader; //用于全局初始化
private static ImageLoaderConfiguration configuration;//默认的ImageLoader配置
private final String DRAWABLE_PREFIX = "drawable://";//用于加载drawable图像 private static class Holder {
private static final ImageLoaderTool loaderTool = new ImageLoaderTool();
} public static ImageLoaderTool getInstance() {
if (imageLoader == null || configuration == null) {
throw new RuntimeException("Must be call the method InitImageLoader(Context context) in Application");
}
return Holder.loaderTool;
} //
// 初始化ImageLoader
//
// @param context 在APP中
//
public static void initImageLoader(Context context) {
File diskCache = StorageUtils.getOwnCacheDirectory(context, "TJD_NBA/");
if (configuration == null) {
configuration = new ImageLoaderConfiguration.Builder(context)
.diskCache(new UnlimitedDiskCache(diskCache))
.diskCacheFileNameGenerator(new Md5FileNameGenerator()) //md5加密
.memoryCacheSize(1024 * 2)//缓存最大字节
.memoryCache(new LruMemoryCache(5 * 1024 * 1024))//解决缓存listview滑动后显示默认图
.memoryCacheExtraOptions(800, 760)// 保存每个缓存图片的最大长和宽
.diskCacheFileCount(100) //缓存的File数量
.build();
}
if (imageLoader == null) {
imageLoader = ImageLoader.getInstance();
imageLoader.init(configuration);
}
} //
// 默认图片加载参数
//
private static DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisk(true)
.cacheInMemory(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.EXACTLY)
.showImageOnFail(R.drawable.side_nav_bar)
.showImageForEmptyUri(R.drawable.side_nav_bar)
.showImageOnLoading(R.drawable.side_nav_bar)
.delayBeforeLoading(1000)
.considerExifParams(true) //是否考虑JPEG图像EXIF参数(旋转,翻转)
.build(); //
// 加载普通图片
//
// @param url
// @param imageView
//
public void loadImage(String url, ImageView imageView) {
imageLoader.displayImage(url, imageView, defaultOptions);
} //
// 加载drawable图片,不能加载系统的drawable 即android:drawable
//
// @param resid
// @param imageView
//
public void loadImageFromDrawable(int resid, ImageView imageView) {
imageLoader.displayImage(DRAWABLE_PREFIX + resid, imageView);
} }

使用ImageLoader时加载相同URL的问题

//使用displayImage,而不使用loadImage,因为loadImage会导致当同时加载同一个url的时候出现task被取消的情况
//详情见https://github.com/nostra13/Android-Universal-Image-Loader/issues/804

1
2
3
// 解决方法
ImageSize size = new ImageSize(Functions.getScreenWidthPix(getActivity()), Functions.getScreenHeightPix(getActivity()));
NonViewAware imageAware = new NonViewAware(size, ViewScaleType.CROP);

解决listvie宽度设置wwrap_content无效的方法

stackoverflow大佬

现象
listview宽度设置wrap_content无效
解决办法,添加FrameLayout跟LinearLayout设置weight

修改前代码

1
2
3
4
5
6
7
8
9
10
11
12
<ListView
android:id="@+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:background="黑色"
android:divider="@null"
android:gravity="center"
android:horizontalSpacing="7dp"
android:numColumns="4"
android:paddingLeft="@dimen/common_layout_margin_15dp"
android:paddingRight="@dimen/common_layout_margin_15dp"></ListView>

修改后代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"> <ListView
android:id="@+id/listView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:background="黑色"
android:divider="@null"
android:gravity="center"
android:horizontalSpacing="7dp"
android:numColumns="4"
android:paddingLeft="@dimen/common_layout_margin_15dp"
android:paddingRight="@dimen/common_layout_margin_15dp"></ListView> <FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.7"
android:background="蓝色" /> </LinearLayout>

本文标题:ImageLoader的理解

文章作者:TanJunDang

发布时间:2015年09月17日 - 00时00分

最后更新:2018年05月14日 - 15时44分

原始链接:http://TanJunDang.github.io/2015/09/17/ImageLoaderTool/

https://tanjundang.github.io/2015/09/17/ImageLoaderTool/

ImageLoader作用 AAAA的更多相关文章

  1. 转:iOS程序main函数之前发生了什么

    原文地址:http://blog.sunnyxx.com/2014/08/30/objc-pre-main/ 我是前言 一个iOS app的main()函数位于main.m中,这是我们熟知的程序入口. ...

  2. 今日头条- iOS客户端 启动速度优化实践

    版权声明 作者:今日头条iOS团队 原文:https://techblog.toutiao.com/2017/01/17/iosspeed/ 应用启动时间,直接影响用户对一款应用的判断和使用体验.头条 ...

  3. iOS程序main函数之前发生了什么

    我是前言 一个iOS app的main()函数位于main.m中,这是我们熟知的程序入口.但对objc了解更多之后发现,程序在进入我们的main函数前已经执行了很多代码,比如熟知的+ load方法等. ...

  4. DNS域名解析中A、AAAA、CNAME、MX、NS、TXT、SRV、SOA、PTR各项记录的作用

    名注册完成后首先需要做域名解析,域名解析就是把域名指向网站所在服务器的IP,让人们通过注册的域名可以访问到网站.IP地址是网络上标识服务器的数字地址,为了方便记忆,使用域名来代替IP地址.域名解析就是 ...

  5. Volley源码分析(2)----ImageLoader

    一:imageLoader 先来看看如何使用imageloader: public void showImg(View view){ ImageView imageView = (ImageView) ...

  6. Volley(四)—— ImageLoader & NetworkImageView

    Volley(四)—— ImageLoader & NetworkImageView ImageLoader是一个加载网络图片的封装类,其内部还是由ImageRequest来实现的.但因为源码 ...

  7. ImageLoader实现图片异步加载

    ImageLoader是一个广泛使用的图片库,在向网络请求图片时,使用imageView和smartView常会产生outofmemory错误,这时ImageLoader可以起到很大的作用,主要有如下 ...

  8. ImageLoader(多线程网络图片加载)+本地缓存 for windowsphone 7

    搞了好长一阵子wp,做点好事. C/S手机app中应用最多的是  获取网络图片,缓存到本地,展示图片 本次主要对其中的delay:LowProfileImageLoader进行修改,在获取图片的时候, ...

  9. mybatis中@Param的用法和作用

    用注解来简化xml配置的时候,@Param注解的作用是给参数命名,参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中 我们先来看Mapper接口中的@Select方法 package Ma ...

随机推荐

  1. 代码使用了php的包管理器composer,include到你的php脚本

    使用数据库进行crontab配置管理,除非你能够保证数据库的请求能够在长时间内保持稳定响应的话.推荐使用nosql类型的cache存储,同时做好持久化备份. 测试代码: define('DS', DI ...

  2. Docker 学习应用篇之三: Docker的简单实用

    安装完Docker之后,我们就可以简单的使用Docker,来体会Docker的用处. 首先看下Docker的常用命令,都是我在实用Docker的时候用到的命令: docker常用命令: $ docke ...

  3. PyQT5-QSlide滑块

    """ QSlider:是一个小滑块组件,这个小滑块能够被拖着一起滑动,用于通常修改具有一定范围的数据 Author: dengyexun DateTime: 2018. ...

  4. 理解CopyOnWriteArrayList

    CopyOnWriteArrayList,顾名思义,Write的时候总是要Copy,也就是说对于任何可变的操作(add.set.remove)都是伴随复制这个动作的 A thread-safe var ...

  5. javaScript高级教程(九) ------javascript对象字面量--------困扰已久的问题

    在编程语言中,字面量是一种表示值的记法.例如,"Hello, World!" 在许多语言中都表示一个字符串字面量(string literal ),JavaScript也不例外. ...

  6. dedecms网站迁移时记得将安装目录放空 附迁移的正确方法

    这段时间在赶一些新项目,我们建站一般都在本地服务器搭建起来,测试得差不多了才传到网上,这样对蜘蛛也相对友好一些,要不然改来改去变化太大给搜索引擎的第一印象很不好.但是由于本地环境和服务器环境还是有一些 ...

  7. android侧滑删除,模仿qq跟进item显示删除按钮

    今天所写的代码只是为了个人以后查询方便,如果你参考了并且在使用中遇到问题也可以在这里直接回复我 SwipeDelMenuLayout: 效果图: item布局: <?xml version=&q ...

  8. 13 jmeter性能测试实战--FTP程序

    需求 上传一个文件到服务器(put),下载一个文件到本地(get). 测试步骤 1.创建一个线程组. 2.线程组-->添加-->配置元件-->FTP请求缺省值(可有可无,相当于给“服 ...

  9. byte处理的几种方法

    /** * 字符串转16进制byte * @param * @return * @throws Exception * @author hw * @date 2018/10/19 9:47 */ pr ...

  10. 发现《深入理解C++11》中扩展的friend代码的错误

    目前在总结现代C++的新特性,看了<深入理解C++11>这本书. 今天看到扩展的friend语法这一节,遇到了问题.本节电子版内容参见:https://book.2cto.com/2013 ...