全面解析Android的开源图片框架Universal-Image-Loader

2019-12-10 18:34:04丽君

if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) { 
   L.d(LOG_LOAD_IMAGE_FROM_NETWORK, memoryCacheKey); 
   loadedFrom = LoadedFrom.NETWORK; 
 
   String imageUriForDecoding = uri; 
   if (options.isCacheOnDisk() && tryCacheImageOnDisk()) { 
    imageFile = configuration.diskCache.get(uri); 
    if (imageFile != null) { 
     imageUriForDecoding = Scheme.FILE.wrap(imageFile.getAbsolutePath()); 
    } 
   } 
 
   checkTaskNotActual(); 
   bitmap = decodeImage(imageUriForDecoding); 
 
   if (bitmap == null || bitmap.getWidth() <= 0 || bitmap.getHeight() <= 0) { 
    fireFailEvent(FailType.DECODING_ERROR, null); 
   } 
  } 

第1行表示从文件缓存中获取的Bitmap为null,或者宽高为0,就去网络上面获取Bitmap,来到第6行代码是否配置了DisplayImageOptions的isCacheOnDisk,表示是否需要将Bitmap对象保存在文件系统中,一般我们需要配置为true, 默认是false这个要注意下,然后就是执行tryCacheImageOnDisk()方法,去服务器上面拉取图片并保存在本地文件中

private Bitmap decodeImage(String imageUri) throws IOException { 
 ViewScaleType viewScaleType = imageAware.getScaleType(); 
 ImageDecodingInfo decodingInfo = new ImageDecodingInfo(memoryCacheKey, imageUri, uri, targetSize, viewScaleType, 
   getDownloader(), options); 
 return decoder.decode(decodingInfo); 
} 
 
/** @return <b>true</b> - if image was downloaded successfully; <b>false</b> - otherwise */ 
private boolean tryCacheImageOnDisk() throws TaskCancelledException { 
 L.d(LOG_CACHE_IMAGE_ON_DISK, memoryCacheKey); 
 
 boolean loaded; 
 try { 
  loaded = downloadImage(); 
  if (loaded) { 
   int width = configuration.maxImageWidthForDiskCache; 
   int height = configuration.maxImageHeightForDiskCache; 
    
   if (width > 0 || height > 0) { 
    L.d(LOG_RESIZE_CACHED_IMAGE_FILE, memoryCacheKey); 
    resizeAndSaveImage(width, height); // TODO : process boolean result 
   } 
  } 
 } catch (IOException e) { 
  L.e(e); 
  loaded = false; 
 } 
 return loaded; 
} 
 
private boolean downloadImage() throws IOException { 
 InputStream is = getDownloader().getStream(uri, options.getExtraForDownloader()); 
 return configuration.diskCache.save(uri, is, this); 
}