Android Universal ImageLoader 缓存图片

2019-12-10 19:20:30于丽

File cacheDir =StorageUtils.getOwnCacheDirectory(this, "imageloader/Cache"); 
ImageLoaderConfigurationconfig = new ImageLoaderConfiguration 
.Builder(this) 
.memoryCacheExtraOptions(480, 800) // maxwidth, max height,即保存的每个缓存文件的最大长宽 
.threadPoolSize(3)//线程池内加载的数量 
.threadPriority(Thread.NORM_PRIORITY -2) 
.denyCacheImageMultipleSizesInMemory() 
.memoryCache(new UsingFreqLimitedMemoryCache(2* 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现 
.memoryCacheSize(2 * 1024 * 1024) 
.discCacheSize(50 * 1024 * 1024) 
.discCacheFileNameGenerator(newMd5FileNameGenerator())//将保存的时候的URI名称用MD5 加密 
.tasksProcessingOrder(QueueProcessingType.LIFO) 
.discCacheFileCount(100) //缓存的文件数量 
.discCache(new UnlimitedDiscCache(cacheDir))//自定义缓存路径 
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) 
.imageDownloader(new BaseImageDownloader(this,5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间 
.writeDebugLogs() // Remove for releaseapp 
.build();//开始构建 
ImageLoader.getInstance().init(config); 

得到imageLoader

ImageLoader imageLoader imageLoader = ImageLoader.getInstance(); 

使用过程:

(1)图像操作是否参与缓存以及图像效果的配置操作

DisplayImageOptions options = new DisplayImageOptions.Builder() 
.showImageOnLoading(R.drawable.ic_stub) //加载图片时的图片 
.showImageForEmptyUri(R.drawable.ic_empty) //没有图片资源时的默认图片 
.showImageOnFail(R.drawable.ic_error) //加载失败时的图片 
.cacheInMemory(true) //启用内存缓存 
.cacheOnDisk(true) //启用外存缓存 
.considerExifParams(true) //启用EXIF和JPEG图像格式 
.displayer(new RoundedBitmapDisplayer(20)) //设置显示风格这里是圆角矩形 
.build(); 

DisplayImageOptions以下是所有默认配置参数根据需求可以自定义配置

private int imageResOnLoading = 0; 
private int imageResForEmptyUri = 0; 
private int imageResOnFail = 0; 
private Drawable imageOnLoading = null; 
private Drawable imageForEmptyUri = null; 
private Drawable imageOnFail = null; 
private boolean resetViewBeforeLoading = false; 
private boolean cacheInMemory = false; 
private boolean cacheOnDisk = false; 
private ImageScaleType imageScaleType = ImageScaleType.IN_SAMPLE_POWER_OF_2; 
private Options decodingOptions = new Options(); 
private int delayBeforeLoading = 0; 
private boolean considerExifParams = false; 
private Object extraForDownloader = null; 
private BitmapProcessor preProcessor = null; 
private BitmapProcessor postProcessor = null; 
private BitmapDisplayer displayer = DefaultConfigurationFactory.createBitmapDisplayer(); 
private Handler handler = null; 
private boolean isSyncLoading = false;