ImageLoader用法总结

2024-05-08 17:08
文章标签 总结 用法 imageloader

本文主要是介绍ImageLoader用法总结,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1,配置方法

1,在Gradle中加入依赖
compile files('libs/universal-image-loader-1.9.4.jar')
2,导入jar包 universal-image-loader-1.9.4.jar
3,代码如下
首先在Application中
ImageLoader.init(getApplicationContext());
其次
public class
ImageLoader { public static final String TAG = "--ljj-- ImageLoader"; private static DisplayImageOptions options; private static DisplayImageOptions.Builder builder; private static Context applicationContext; private static boolean isShowPicture ; public static void init(Context applicationContext) { ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(applicationContext) .threadPoolSize(Thread.NORM_PRIORITY - 2)//线程池大小 .denyCacheImageMultipleSizesInMemory()//否定高速缓存图像多大小在内存中 .diskCacheFileNameGenerator(new Md5FileNameGenerator())//磁盘缓存文件名生成器MD5 .tasksProcessingOrder(QueueProcessingType.LIFO)//后进先出法 .threadPoolSize(3) .memoryCache(new WeakMemoryCache()) .memoryCacheSize(2 * 1024 * 1024) .memoryCacheSizePercentage(13) .denyCacheImageMultipleSizesInMemory() .writeDebugLogs()//编写调试日志 .build();//建立 com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(imageLoaderConfiguration); options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.image_loading)//加载图片时显示的默认图片 .showImageForEmptyUri(R.drawable.default_error)//显示空URI的图像 .showImageOnFail(R.drawable.default_error)//显示图像失败 .cacheInMemory(true)//是否添加到内存缓存中 .cacheOnDisk(true)//是否添加到硬盘缓存中 .considerExifParams(true) .bitmapConfig(Bitmap.Config.RGB_565) .build(); builder = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.image_loading)//加载图片时显示的默认图片 .showImageForEmptyUri(R.drawable.default_error)//显示空URI的图像 .showImageOnFail(R.drawable.default_error)//显示图像失败 .cacheInMemory(true)//是否添加到内存缓存中 .cacheOnDisk(true)//是否添加到硬盘缓存中 .bitmapConfig(Bitmap.Config.RGB_565) .considerExifParams(true); ImageLoader.applicationContext = applicationContext; } /** * 普通图片加载 * * @param imageURL * @param imageView */ public static void displayImage(String imageURL, ImageView imageView) { if(isShowPicture == true){ imageView.setImageResource(R.drawable.default_error); }else{ com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(urlTransformation(imageURL), imageView, options); } } /** * 普通图片加载 * * @param image 图片地址 * @param imageView 控件 */ public static void displayImage(int image, ImageView imageView) { displayImage("drawable://" + image, imageView); } /** * 圆角图片加载 * * @param image 图片地址 * @param imageView 控件 */ public static void displayImage(int image, ImageView imageView, int cornerRadiusPixels) { displayImage("drawable://" + image, imageView, cornerRadiusPixels); } /** * 圆角图片加载 * * @param imageURL 图片地址 * @param imageView 控件 * @param cornerRadiusPixels 圆角直径(控件宽或高) */ public static void displayImage(String imageURL, ImageView imageView, int cornerRadiusPixels) { builder.displayer(new RoundedBitmapDisplayer(Math.round(applicationContext.getResources().getDisplayMetrics().density * cornerRadiusPixels)));// com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(urlTransformation(imageURL), imageView, builder.build()); if(isShowPicture == true){ imageView.setImageResource(R.drawable.default_error); }else{ com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(urlTransformation(imageURL), imageView, builder.build()); } } /** * 高斯模糊图片加载 * * @param image 图片地址 * @param imageView 控件 */ public static void displayBlur(int image, ImageView imageView) { displayBlur("drawable://" + image, imageView); } /** * 高斯模糊图片加载 * * @param imageURL 图片地址 * @param imageView 控件 */ public static void displayBlur(String imageURL, ImageView imageView) {// com.nostra13.universalimageloader.core.ImageLoader.getInstance().loadImage(urlTransformation(imageURL), new BlurImageLoadingListener(imageView)); if(isShowPicture == true){ imageView.setImageResource(R.drawable.default_error); }else{ com.nostra13.universalimageloader.core.ImageLoader.getInstance().loadImage(urlTransformation(imageURL), new BlurImageLoadingListener(imageView)); } } /** * 水平方向模糊度 */ private static float hRadius = 3; /** * 竖直方向模糊度 */ private static float vRadius = 3; /** * 模糊迭代度 */ private static int iterations = 2; public static Bitmap createBitmap(int width, int height, Bitmap.Config config) { Bitmap bitmap = null; try { bitmap = Bitmap.createBitmap(width, height, config); } catch (OutOfMemoryError e) { while(bitmap == null) { System.gc(); System.runFinalization(); bitmap = createBitmap(width, height, config); } } return bitmap; } /** * 高斯模糊 */ public static Bitmap BoxBlurFilter(Bitmap bmp) { int width = bmp.getWidth(); int height = bmp.getHeight(); int[] inPixels = new int[width * height]; int[] outPixels = new int[width * height]; Bitmap bitmap = createBitmap(width, height, Bitmap.Config.RGB_565); bmp.getPixels(inPixels, 0, width, 0, 0, width, height); for (int i = 0; i < iterations; i++) { blur(inPixels, outPixels, width, height, hRadius); blur(outPixels, inPixels, height, width, vRadius); } blurFractional(inPixels, outPixels, width, height, hRadius); blurFractional(outPixels, inPixels, height, width, vRadius); bitmap.setPixels(inPixels, 0, width, 0, 0, width, height);// Drawable drawable = new BitmapDrawable(bitmap); return bitmap; } private static void blur(int[] in, int[] out, int width, int height, float radius) { int widthMinus1 = width - 1; int r = (int) radius; int tableSize = 2 * r + 1; int divide[] = new int[256 * tableSize]; for (int i = 0; i < 256 * tableSize; i++) divide[i] = i / tableSize; int inIndex = 0; for (int y = 0; y < height; y++) { int outIndex = y; int ta = 0, tr = 0, tg = 0, tb = 0; for (int i = -r; i <= r; i++) { int rgb = in[inIndex + clamp(i, 0, width - 1)]; ta += (rgb >> 24) & 0xff; tr += (rgb >> 16) & 0xff; tg += (rgb >> 8) & 0xff; tb += rgb & 0xff; } for (int x = 0; x < width; x++) { out[outIndex] = (divide[ta] << 24) | (divide[tr] << 16) | (divide[tg] << 8) | divide[tb]; int i1 = x + r + 1; if (i1 > widthMinus1) i1 = widthMinus1; int i2 = x - r; if (i2 < 0) i2 = 0; int rgb1 = in[inIndex + i1]; int rgb2 = in[inIndex + i2]; ta += ((rgb1 >> 24) & 0xff) - ((rgb2 >> 24) & 0xff); tr += ((rgb1 & 0xff0000) - (rgb2 & 0xff0000)) >> 16; tg += ((rgb1 & 0xff00) - (rgb2 & 0xff00)) >> 8; tb += (rgb1 & 0xff) - (rgb2 & 0xff); outIndex += height; } inIndex += width; } } private static void blurFractional(int[] in, int[] out, int width, int height, float radius) { radius -= (int) radius; float f = 1.0f / (1 + 2 * radius); int inIndex = 0; for (int y = 0; y < height; y++) { int outIndex = y; out[outIndex] = in[0]; outIndex += height; for (int x = 1; x < width - 1; x++) { int i = inIndex + x; int rgb1 = in[i - 1]; int rgb2 = in[i]; int rgb3 = in[i + 1]; int a1 = (rgb1 >> 24) & 0xff; int r1 = (rgb1 >> 16) & 0xff; int g1 = (rgb1 >> 8) & 0xff; int b1 = rgb1 & 0xff; int a2 = (rgb2 >> 24) & 0xff; int r2 = (rgb2 >> 16) & 0xff; int g2 = (rgb2 >> 8) & 0xff; int b2 = rgb2 & 0xff; int a3 = (rgb3 >> 24) & 0xff; int r3 = (rgb3 >> 16) & 0xff; int g3 = (rgb3 >> 8) & 0xff; int b3 = rgb3 & 0xff; a1 = a2 + (int) ((a1 + a3) * radius); r1 = r2 + (int) ((r1 + r3) * radius); g1 = g2 + (int) ((g1 + g3) * radius); b1 = b2 + (int) ((b1 + b3) * radius); a1 *= f; r1 *= f; g1 *= f; b1 *= f; out[outIndex] = (a1 << 24) | (r1 << 16) | (g1 << 8) | b1; outIndex += height; } out[outIndex] = in[width - 1]; inIndex += width; } } private static int clamp(int x, int a, int b) { return (x < a) ? a : (x > b) ? b : x; } /** * 地址转换 * 把相对地址转换成实际地址 * * @param imageURL * @return */ public static String urlTransformation(String imageURL) { if (imageURL == null || imageURL.trim().isEmpty()) { return "drawable://" + R.drawable.default_error; } else if (imageURL.matches(NO_TRANSFORMATION)) { Log.e(TAG, "不转换 " + imageURL); return imageURL; } else { Log.e(TAG, "转换 " + HttpService.SERVER_ADDRESS + imageURL); return HttpService.SERVER_ADDRESS + imageURL; } } public static String FILE = "^[Ff][Ii][Ll][Ee]://[\\S]*"; public static String HTTP = "^[Hh][Tt][Tt][Pp]://[\\S]*"; public static String HTTPS = "^[Hh][Tt][Tt][Pp][Ss]://[\\S]*"; public static String CONTENT = "^[Cc][Oo][Nn][Tt][Ee][Nn][Tt]://[\\S]*"; public static String ASSETS = "^[Aa][Ss][Ee][Tt][Ss]://[\\S]*"; public static String DRAWABLE = "^[Dd][Rr][Aa][Ww][Aa][Bb][Ll][Ee]://[\\S]*"; public static String NO_TRANSFORMATION = "(" + FILE + ")|(" + HTTP + ")|(" + HTTPS + ")|(" + CONTENT + ")|(" + ASSETS + ")|(" + FILE + ")|(" + DRAWABLE + ")"; /** * url转成drawable * 并添加到imageView * * @param url 网络图片地址 * @param imageView 图片控件 */ public static void loadImageFromNetwork(final String url, final ImageView imageView) { new Thread(new Runnable() { Drawable loadImageDrawable = loadImageFromNetwork(url); @Override public void run() { // 更新主线程UI资源 imageView.post(new Runnable() { @Override public void run() { imageView.setImageDrawable(loadImageDrawable); } }); } }).start(); //线程启动 } /** * url drawable * * @param imageUrl 图片地址 * @return */ public static Drawable loadImageFromNetwork(String imageUrl) { Drawable drawable = null; try { drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.jpg"); } catch (IOException e) { Log.d("test", e.getMessage()); } return drawable; } public static boolean isShowPicture() { return isShowPicture; } public static void setIsShowPicture(boolean isShowPicture) { ImageLoader.isShowPicture = isShowPicture; } public static void onDestory(){ com.nostra13.universalimageloader.core.ImageLoader.getInstance().clearMemoryCache(); }}

最后,在需要的地方直接引用就可以
ImageLoader.displayImage(图片地址,图片控件);


2,开发过程中遇到的bug
虽然这个框架有很好的缓存机制,有效的避免了OOM的产生,一般的情况下产生OOM的概率比较小,但是并不能保证OutOfMemoryError永远不发生。在开发过程中稍不留意就可能会遇到内存溢出的问题,根据自己的开发经验,为了避免内存溢出的问题,总结几点注意。
1,在DisplayImageOptions选项中配置bitmapConfig为Bitmap.Config.RGB_565,因为默认是ARGB_8888, 使用RGB_565会比使用ARGB_8888少消耗2倍 的内存;
2,在DisplayImageOptions选项中设置.imageScaleType(ImageScaleType.IN_SAMPLE_INT)或者imageScaleType(ImageScaleType.EXACTLY);
3,
protected void onDestroy() {super.onDestroy();ImageLoader.onDestory();
}


这篇关于ImageLoader用法总结的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/970918

相关文章

前端高级CSS用法示例详解

《前端高级CSS用法示例详解》在前端开发中,CSS(层叠样式表)不仅是用来控制网页的外观和布局,更是实现复杂交互和动态效果的关键技术之一,随着前端技术的不断发展,CSS的用法也日益丰富和高级,本文将深... 前端高级css用法在前端开发中,CSS(层叠样式表)不仅是用来控制网页的外观和布局,更是实现复杂交

揭秘Python Socket网络编程的7种硬核用法

《揭秘PythonSocket网络编程的7种硬核用法》Socket不仅能做聊天室,还能干一大堆硬核操作,这篇文章就带大家看看Python网络编程的7种超实用玩法,感兴趣的小伙伴可以跟随小编一起... 目录1.端口扫描器:探测开放端口2.简易 HTTP 服务器:10 秒搭个网页3.局域网游戏:多人联机对战4.

MyBatis 动态 SQL 优化之标签的实战与技巧(常见用法)

《MyBatis动态SQL优化之标签的实战与技巧(常见用法)》本文通过详细的示例和实际应用场景,介绍了如何有效利用这些标签来优化MyBatis配置,提升开发效率,确保SQL的高效执行和安全性,感... 目录动态SQL详解一、动态SQL的核心概念1.1 什么是动态SQL?1.2 动态SQL的优点1.3 动态S

java之Objects.nonNull用法代码解读

《java之Objects.nonNull用法代码解读》:本文主要介绍java之Objects.nonNull用法代码,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录Java之Objects.nonwww.chinasem.cnNull用法代码Objects.nonN

JavaScript Array.from及其相关用法详解(示例演示)

《JavaScriptArray.from及其相关用法详解(示例演示)》Array.from方法是ES6引入的一个静态方法,用于从类数组对象或可迭代对象创建一个新的数组实例,本文将详细介绍Array... 目录一、Array.from 方法概述1. 方法介绍2. 示例演示二、结合实际场景的使用1. 初始化二

java常见报错及解决方案总结

《java常见报错及解决方案总结》:本文主要介绍Java编程中常见错误类型及示例,包括语法错误、空指针异常、数组下标越界、类型转换异常、文件未找到异常、除以零异常、非法线程操作异常、方法未定义异常... 目录1. 语法错误 (Syntax Errors)示例 1:解决方案:2. 空指针异常 (NullPoi

一文带你了解SpringBoot中启动参数的各种用法

《一文带你了解SpringBoot中启动参数的各种用法》在使用SpringBoot开发应用时,我们通常需要根据不同的环境或特定需求调整启动参数,那么,SpringBoot提供了哪些方式来配置这些启动参... 目录一、启动参数的常见传递方式二、通过命令行参数传递启动参数三、使用 application.pro

关于@RequestParam的主要用法详解

《关于@RequestParam的主要用法详解》:本文主要介绍关于@RequestParam的主要用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1. 基本用法2. 默认值3. 可选参数4. 绑定到对象5. 绑定到集合或数组6. 绑定到 Map7. 处理复杂类

SQL中的CASE WHEN用法小结

《SQL中的CASEWHEN用法小结》文章详细介绍了SQL中的CASEWHEN函数及其用法,包括简单CASEWHEN和CASEWHEN条件表达式两种形式,并通过多个实际场景展示了如何使用CASEWH... 目录一、简单CASE WHEN函数:二、CASE WHEN条件表达式函数三、常用场景场景1:不同状态展

Linux find 命令完全指南及核心用法

《Linuxfind命令完全指南及核心用法》find是Linux系统最强大的文件搜索工具,支持嵌套遍历、条件筛选、执行动作,下面给大家介绍Linuxfind命令完全指南,感兴趣的朋友一起看看吧... 目录一、基础搜索模式1. 按文件名搜索(精确/模糊匹配)2. 排除指定目录/文件二、根据文件类型筛选三、时间