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

相关文章

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

Python itertools中accumulate函数用法及使用运用详细讲解

《Pythonitertools中accumulate函数用法及使用运用详细讲解》:本文主要介绍Python的itertools库中的accumulate函数,该函数可以计算累积和或通过指定函数... 目录1.1前言:1.2定义:1.3衍生用法:1.3Leetcode的实际运用:总结 1.1前言:本文将详

MyBatis-Flex BaseMapper的接口基本用法小结

《MyBatis-FlexBaseMapper的接口基本用法小结》本文主要介绍了MyBatis-FlexBaseMapper的接口基本用法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具... 目录MyBATis-Flex简单介绍特性基础方法INSERT① insert② insertSelec

Python中连接不同数据库的方法总结

《Python中连接不同数据库的方法总结》在数据驱动的现代应用开发中,Python凭借其丰富的库和强大的生态系统,成为连接各种数据库的理想编程语言,下面我们就来看看如何使用Python实现连接常用的几... 目录一、连接mysql数据库二、连接PostgreSQL数据库三、连接SQLite数据库四、连接Mo

深入解析Spring TransactionTemplate 高级用法(示例代码)

《深入解析SpringTransactionTemplate高级用法(示例代码)》TransactionTemplate是Spring框架中一个强大的工具,它允许开发者以编程方式控制事务,通过... 目录1. TransactionTemplate 的核心概念2. 核心接口和类3. TransactionT

数据库使用之union、union all、各种join的用法区别解析

《数据库使用之union、unionall、各种join的用法区别解析》:本文主要介绍SQL中的Union和UnionAll的区别,包括去重与否以及使用时的注意事项,还详细解释了Join关键字,... 目录一、Union 和Union All1、区别:2、注意点:3、具体举例二、Join关键字的区别&php

Git提交代码详细流程及问题总结

《Git提交代码详细流程及问题总结》:本文主要介绍Git的三大分区,分别是工作区、暂存区和版本库,并详细描述了提交、推送、拉取代码和合并分支的流程,文中通过代码介绍的非常详解,需要的朋友可以参考下... 目录1.git 三大分区2.Git提交、推送、拉取代码、合并分支详细流程3.问题总结4.git push

Kubernetes常用命令大全近期总结

《Kubernetes常用命令大全近期总结》Kubernetes是用于大规模部署和管理这些容器的开源软件-在希腊语中,这个词还有“舵手”或“飞行员”的意思,使用Kubernetes(有时被称为“... 目录前言Kubernetes 的工作原理为什么要使用 Kubernetes?Kubernetes常用命令总

Python中实现进度条的多种方法总结

《Python中实现进度条的多种方法总结》在Python编程中,进度条是一个非常有用的功能,它能让用户直观地了解任务的进度,提升用户体验,本文将介绍几种在Python中实现进度条的常用方法,并通过代码... 目录一、简单的打印方式二、使用tqdm库三、使用alive-progress库四、使用progres

oracle中exists和not exists用法举例详解

《oracle中exists和notexists用法举例详解》:本文主要介绍oracle中exists和notexists用法的相关资料,EXISTS用于检测子查询是否返回任何行,而NOTE... 目录基本概念:举例语法pub_name总结 exists (sql 返回结果集为真)not exists (s