ImageLoader用法总结

来源:互联网 发布:手机java小游戏代码 编辑:程序博客网 时间:2024/05/22 10:27

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


0 0
原创粉丝点击