ImageLoader使用记录

ImageLoader使用记录

导读

ImageLoader的目的是提供一个强大的、灵活的和高度可定制的工具用来进行图像的加载、缓存和显示。它提供了大量的配置选项,并能很好地控制图像加载和缓存的过程。但是很遗憾,这个项目已经在2015年11月27日停止维护了。具体内容可以参考Universal Image Loader(GitHub地址)

使用方法

先要配置ImageLoaderConfiguration这个类实现全局ImageLoader的实现情况。可以选择在Application中初始化设置该类,或者自定义一个类继承Application。
使用ImageLoader进行图片加载的时候,先要实例化ImageLoader,在每个布局里面都要实例化后再使用。
对显示图片的各种格式DisplayImageOptions进行设置。
调用ImageLoader中的方法对图片进行显示,可以设置为默认配置,或者自定义配置,也可为加载过程添加监听事件。

可以参考如下几篇博客:
关于如何配置ImageLoader,请看图片异步加载类库的使用(超详细配置)
使用范例,请看Android开源框架Universal-Image-Loader详解
以及Android UI-开源框架ImageLoader的完美例子,这里博主自己搭了个测试项目,测试了ListView、GridView中使用ImageLoader的情况。
又发现了一篇好博文,关于ImageLoader的源码分析胖虎谈ImageLoader框架(一)

使用范例

在MyApplication类配置ImageLoader

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        initImageLoader(getApplicationContext());
    }
    private void initImageLoader(Context context) {
        File cacheDir = StorageUtils.getOwnCacheDirectory(context, "imageloader/Cache");
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(context)
                .diskCache(new UnlimitedDiskCache(cacheDir))
                .build();
        ImageLoader.getInstance().init(configuration);
    }
}

解析json数据,将图片保存至本地

/**
     * 保存用户头像至文件
     * @param str 取得的头像json数据
     */
    private void saveUserImage(String str) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(str);
            String bitmapString = jsonObject.getString("content");
            byte[] bytes = Base64.decode(bitmapString, Base64.DEFAULT);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            File bitmapFile = new File(this.getApplication().getFilesDir().getAbsolutePath() + "userImage");
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(bitmapFile));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

根据本地文件,显示图片

//从本地读取用户头像并显示
    private void showUserImage(View view) {
        String filePath = "file://" + getActivity().getApplication().getFilesDir().getAbsolutePath() + "userImage";
        Log.i("dxl", filePath);
        DisplayImageOptions options;
        options = new DisplayImageOptions.Builder()
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                .displayer(new RoundedBitmapDisplayer(100))//设置圆角图片
                .build();
        ImageLoader.getInstance().displayImage(filePath, ivUserImage, options);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值