图片加载框架简单介绍<一> ImageLoader 的基本使用

  • **ImageLoader简单介绍 **
    ImageLoader 是最早开源的 Android 图片缓存库, 强大的缓存机制, 早期使用这个图片加载框架的Android应用非常多, 至今仍然有不少 Android 开发者在使用。

  • 使用第一步,配置一些参数

DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.ic_stub) // 设置图片下载期间显示的图片
        .showImageOnLoading(R.drawable.ic_empty)    //设置下载过程中图片显示   
        .showImageForEmptyUri(R.drawable.ic_empty) // 设置图片Uri为空或是错误的时候显示的图片
        .showImageOnFail(R.drawable.ic_error) // 设置图片加载或解码过程中发生错误显示的图片
        .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
        .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
        .build(); // 创建配置过得DisplayImageOption对象

ImageLoaderConfiguration config = new ImageLoaderConfiguration
        .Builder(
        context.getApplicationContext())
        .defaultDisplayImageOptions(options)
        .threadPriority(Thread.NORM_PRIORITY - 2)
        .denyCacheImageMultipleSizesInMemory()
        .discCacheFileNameGenerator(new Md5FileNameGenerator())
        .tasksProcessingOrder(QueueProcessingType.LIFO)
        .build();
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(config);   

因为ImageLoader使用的是单例模式。所以上面的这些配置(还有一些其他配置选项,这里就不一一写出来了),在项目中只需要设置一次就可以了。

  • 第二步,获取ImageLoader图片加载框架实例对象
ImageLoader imageLoader = ImageLoader.getInstance(); 

到这里就可以使用获取到的imagerLoader来进行图片加载了,使用imagerLoader加载图片有很多种方式,简单说三种最常用的,然后再把全部加在方法源码贴在后面,根据自己的不同需求,大家再具体使用相应的方法。

  • 根据url把图片展示到imageView控件上(异步加载)
imageLoader.displayImage(imageUri, imageView); 
  • 根据url把图片展示到imageView控件上,并监听图片加载是否完毕(异步加载)
imageLoader.displayImage(imageUrl, imageView, null , new SimpleImageLoadingListener(){

    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        //在这里执行你想要做的事情
    }

}, new ImageLoadingProgressListener(){

    @Override
    public void onProgressUpdate(String imageUri, View view, int current, int total) {
        //在这里执行你想要做的事情,total总进度,current当前加载进度
    }
});

上面代码中仅仅重写了监听对象SimpleImageLoadingListener的onLoadingComplete方法,其实还有其他三个方法:onLoadingStarted(加载开始),onLoadingFailed(加载失败),onLoadingCancelled(加载取消),可以根据自己的具体需要去考虑是否进行重写。

  • 根据url获取到图片文件并返回为位图格式对象(同步加载)
Bitmap bmp = imageLoader.loadImageSync(imageUri);
  • 以下代码为ImageLoader对象加载图片的三大类方法及其重载
    方法loadImage是异步加载,一般需要对加载过程设置监听,待图片资源加载完毕,再手动操作把图片展示到控件上。
    方法displayImage是异步加载,可以不设置监听,待图片资源加载完毕,会自动把图片展示到控件上。
    方法loadImageSync是同步加载,待图片资源加载完毕,直接返回位图资源对象
    //ImageViewAware这个类主要是将ImageView进行一个包装,将  ImageView的强引用变成弱引用,
    //当内存不足的时候,可以更好的回收ImageView对象,还有就是获取ImageView的宽度和高度。
    //这使得我们可以根据ImageView的宽高去对图片进行一个裁剪,减少内存的使用。
    public void displayImage(String uri, ImageAware imageAware) {
        this.displayImage(uri, (ImageAware)imageAware, (DisplayImageOptions)null, (ImageLoadingListener)null, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageAware imageAware, ImageLoadingListener listener) {
        this.displayImage(uri, (ImageAware)imageAware, (DisplayImageOptions)null, listener, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options) {
        this.displayImage(uri, (ImageAware)imageAware, options, (ImageLoadingListener)null, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options, ImageLoadingListener listener) {
        this.displayImage(uri, (ImageAware)imageAware, options, listener, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options, ImageLoadingListener listener, ImageLoadingProgressListener progressListener) {
        this.checkConfiguration();
        if(imageAware == null) {
            throw new IllegalArgumentException("Wrong arguments were passed to displayImage() method (ImageView reference must not be null)");
        } else {
            if(listener == null) {
                listener = this.emptyListener;
            }

            if(options == null) {
                options = this.configuration.defaultDisplayImageOptions;
            }

            if(TextUtils.isEmpty(uri)) {
                this.engine.cancelDisplayTaskFor(imageAware);
                listener.onLoadingStarted(uri, imageAware.getWrappedView());
                if(options.shouldShowImageForEmptyUri()) {
                    imageAware.setImageDrawable(options.getImageForEmptyUri(this.configuration.resources));
                } else {
                    imageAware.setImageDrawable((Drawable)null);
                }

                listener.onLoadingComplete(uri, imageAware.getWrappedView(), (Bitmap)null);
            } else {
                ImageSize targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, this.configuration.getMaxImageSize());
                String memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize);
                this.engine.prepareDisplayTaskFor(imageAware, memoryCacheKey);
                listener.onLoadingStarted(uri, imageAware.getWrappedView());
                Bitmap bmp = (Bitmap)this.configuration.memoryCache.get(memoryCacheKey);
                ImageLoadingInfo imageLoadingInfo;
                if(bmp != null && !bmp.isRecycled()) {
                    L.d("Load image from memory cache [%s]", new Object[]{memoryCacheKey});
                    if(options.shouldPostProcess()) {
                        imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey, options, listener, progressListener, this.engine.getLockForUri(uri));
                        ProcessAndDisplayImageTask displayTask1 = new ProcessAndDisplayImageTask(this.engine, bmp, imageLoadingInfo, defineHandler(options));
                        if(options.isSyncLoading()) {
                            displayTask1.run();
                        } else {
                            this.engine.submit(displayTask1);
                        }
                    } else {
                        options.getDisplayer().display(bmp, imageAware, LoadedFrom.MEMORY_CACHE);
                        listener.onLoadingComplete(uri, imageAware.getWrappedView(), bmp);
                    }
                } else {
                    if(options.shouldShowImageOnLoading()) {
                        imageAware.setImageDrawable(options.getImageOnLoading(this.configuration.resources));
                    } else if(options.isResetViewBeforeLoading()) {
                        imageAware.setImageDrawable((Drawable)null);
                    }

                    imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey, options, listener, progressListener, this.engine.getLockForUri(uri));
                    LoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask(this.engine, imageLoadingInfo, defineHandler(options));
                    if(options.isSyncLoading()) {
                        displayTask.run();
                    } else {
                        this.engine.submit(displayTask);
                    }
                }

            }
        }
    }

    public void displayImage(String uri, ImageView imageView) {
        this.displayImage(uri, (ImageAware)(new ImageViewAware(imageView)), (DisplayImageOptions)null, (ImageLoadingListener)null, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageView imageView, DisplayImageOptions options) {
        this.displayImage(uri, (ImageAware)(new ImageViewAware(imageView)), options, (ImageLoadingListener)null, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageView imageView, ImageLoadingListener listener) {
        this.displayImage(uri, (ImageAware)(new ImageViewAware(imageView)), (DisplayImageOptions)null, listener, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener) {
        this.displayImage(uri, (ImageView)imageView, options, listener, (ImageLoadingProgressListener)null);
    }

    public void displayImage(String uri, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener, ImageLoadingProgressListener progressListener) {
        this.displayImage(uri, (ImageAware)(new ImageViewAware(imageView)), options, listener, progressListener);
    }

    public void loadImage(String uri, ImageLoadingListener listener) {
        this.loadImage(uri, (ImageSize)null, (DisplayImageOptions)null, listener, (ImageLoadingProgressListener)null);
    }

    public void loadImage(String uri, ImageSize targetImageSize, ImageLoadingListener listener) {
        this.loadImage(uri, targetImageSize, (DisplayImageOptions)null, listener, (ImageLoadingProgressListener)null);
    }

    public void loadImage(String uri, DisplayImageOptions options, ImageLoadingListener listener) {
        this.loadImage(uri, (ImageSize)null, options, listener, (ImageLoadingProgressListener)null);
    }

    public void loadImage(String uri, ImageSize targetImageSize, DisplayImageOptions options, ImageLoadingListener listener) {
        this.loadImage(uri, targetImageSize, options, listener, (ImageLoadingProgressListener)null);
    }

    public void loadImage(String uri, ImageSize targetImageSize, DisplayImageOptions options, ImageLoadingListener listener, ImageLoadingProgressListener progressListener) {
        this.checkConfiguration();
        if(targetImageSize == null) {
            targetImageSize = this.configuration.getMaxImageSize();
        }

        if(options == null) {
            options = this.configuration.defaultDisplayImageOptions;
        }

        NonViewAware imageAware = new NonViewAware(uri, targetImageSize, ViewScaleType.CROP);
        this.displayImage(uri, (ImageAware)imageAware, options, listener, progressListener);
    }

    public Bitmap loadImageSync(String uri) {
        return this.loadImageSync(uri, (ImageSize)null, (DisplayImageOptions)null);
    }

    public Bitmap loadImageSync(String uri, DisplayImageOptions options) {
        return this.loadImageSync(uri, (ImageSize)null, options);
    }

    public Bitmap loadImageSync(String uri, ImageSize targetImageSize) {
        return this.loadImageSync(uri, targetImageSize, (DisplayImageOptions)null);
    }

    public Bitmap loadImageSync(String uri, ImageSize targetImageSize, DisplayImageOptions options) {
        if(options == null) {
            options = this.configuration.defaultDisplayImageOptions;
        }

        options = (new Builder()).cloneFrom(options).syncLoading(true).build();
        ImageLoader.SyncImageLoadingListener listener = new ImageLoader.SyncImageLoadingListener();
        this.loadImage(uri, targetImageSize, options, listener);
        return listener.getLoadedBitmap();
    }
  • 对ImageLoader进行封装

    建议大家在使用框架的时候,自己再进行一下二次封装,这样如果以后换框架,整个项目改动的地方会非常少,而且自己封装的东西,用起来肯定会更加得心应手。下面是我自己对ImageLoader进行简单封装生成的一个类,大家可以参考下然后自己封装一个最好。

public class ImagerLoaderUtil {

    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    private Context context;
    private static ImagerLoaderUtil imagerLoaderUtil;

    private ImagerLoaderUtil(Context context) {
        super();
        this.context = context;
    }

    public synchronized static ImagerLoaderUtil getInstance(Context context){
        if(imagerLoaderUtil == null){
            imagerLoaderUtil = new ImagerLoaderUtil(context);
            imagerLoaderUtil.initImageLoader();
        }
        return imagerLoaderUtil;
    }

    public void displayMyImage(String imageUrl, ImageView imageView ){
        imageLoader.displayImage(imageUrl, imageView);
    }

    public void displayMyImage(String imageUrl, ImageView imageView,SimpleImageLoadingListener listener ){
        imageLoader.displayImage(imageUrl, imageView, listener);
    }

    public void displayMyImage(String imageUrl, ImageView imageView, int resourceId){
        DisplayImageOptions tempOptions = new DisplayImageOptions.Builder()
        .cacheInMemory(false)//设置下载的图片是否缓存在内存
        .cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中
        .showImageOnLoading(resourceId)         // 设置图片下载期间显示的图片  
        .showImageForEmptyUri(resourceId)  // 设置图片Uri为空或是错误的时候显示的图片  
        .showImageOnFail(resourceId)       // 设置图片加载或解码过程中发生错误显示的图片  
        .build();
        imageLoader.displayImage(imageUrl, imageView, tempOptions);
    }

    public void displayMyImage(String imageUrl, ImageView imageView, int resourceId, SimpleImageLoadingListener listener) {
        DisplayImageOptions tempOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(false)//设置下载的图片是否缓存在内存
                .cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中
                .showImageOnLoading(resourceId)         // 设置图片下载期间显示的图片
                .showImageForEmptyUri(resourceId)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(resourceId)       // 设置图片加载或解码过程中发生错误显示的图片
                .build();
        imageLoader.displayImage(imageUrl, imageView, tempOptions, listener);
    }

    public void initImageLoader() {
        
        DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.ic_stub) // 设置图片下载期间显示的图片
                .showImageOnLoading(R.drawable.ic_empty)    //设置下载过程中图片显示   
                .showImageForEmptyUri(R.drawable.ic_empty) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.ic_error) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
                .build(); // 创建配置过得DisplayImageOption对象

        ImageLoaderConfiguration config = new ImageLoaderConfiguration
                .Builder(
                context.getApplicationContext())
                .defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .build();
                imageLoader = ImageLoader.getInstance();
                imageLoader.init(config);   
    }
}
  • 最后附上ImagerLoader在gitHub上面的项目地址:点击打开
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341

推荐阅读更多精彩内容

  • 一、简历准备 1、个人技能 (1)自定义控件、UI设计、常用动画特效 自定义控件 ①为什么要自定义控件? Andr...
    lucas777阅读 5,184评论 2 54
  • Volley框架 Volley是Google官方出的一套小而巧的异步请求库,该框架封装的扩展性很强,支持HttpC...
    void_Zhao阅读 10,685评论 2 2
  • 7.1 压缩图片 一、基础知识 1、图片的格式 jpg:最常见的图片格式。色彩还原度比较好,可以支持适当压缩后保持...
    AndroidMaster阅读 2,473评论 0 13
  • title: 第12章 Bitmap的加载和Cachetags: []notebook: Android开发艺术探...
    反复横跳的龙套阅读 1,739评论 0 10
  • 1.什么领带使男性看起来性感、有活力呢?(提示:“性感”总统克林顿曾用它在美国赢取了无数女选民的青睐) 2.人人想...
    IngridWu阅读 292评论 0 0