Glide是Google推荐的图片加载库, 加载图片一般以下面的形式:
Glide.with(context).load(ImgUrl)
.asBitmap()
.error(R.drawable.error)
.placeholder(R.drawable.loading)
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(ImageView);
load对象: String(文件路径,网络地址),File(文件资源),Integer(资源id);
asGif:表示的gif动画,asBitmap:表示静态图
diskCacheStrategy磁盘缓存策略:
(1). DiskCacheStrategy.RESULT:展示小大的图片缓存
(2). DiskCacheStrategy.ALL; 展示在控件中大小图片尺寸和原图都会缓存
(3). DiskCacheStrategy.NONE:不设置缓存
(4). DiskCacheStrategy.SOURCE:原图缓存
placeholder(R.drawable.loading): 目标从加载到展示时的控件的显示状态(多用网络加载动画)
error(R,drawable,error): 加载失败时,控件显示的图片。
into(ImageView): 展示的控件
Glide加载网络图片时, 会将图片缓存一份到本地, 下次再加载的时候优先从缓存中拿取, 提高速度.
如果想获取Glide缓存的图片, 怎么办?
我们都知道 开源框架Universal_Image_Loader 提供 “getDiskCache().get(url)” 去获取图片的本地缓存.
但是Glide并没有提供类似方法.
那么Glide如何获取本地的缓存 ?
Glide提供 downloadOnly() 接口, 可以通过此接口来获取缓存文件. 但是有一个前提:
使用Glide加载图片时, 必须指定diskCacheStrategy磁盘缓存策略为DiskCacheStrategy.ALL 或 DiskCacheStrategy.SOURCE
使用downloadOnly()获取缓存文件(此方法需要在线程中执行, 如果确定文件有缓存, 它会从缓存中读取文件, 很快):
private class GetImageCacheTask extends AsyncTask<String, Void, File> {
private final Context context;
public SaveImageTask(Context context) {
this.context = context;
}
@Override
protected File doInBackground(String... params) {
String imgUrl = params[0];
try {
return Glide.with(context)
.load(imgUrl)
.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
} catch (Exception ex) {
return null;
}
}
@Override
protected void onPostExecute(File result) {
if (result == null) {
return;
}
//此path就是对应文件的缓存路径
String path = result.getPath();
//将缓存文件copy, 命名为图片格式文件
copyFile(path, newPath);
}
}
上面的path就是对应图片的缓存地址, 类似于: /data/data/包名/cache/image_manager_disk_cache/6872faf4075a6461f3d7ceb2e5ff625beeaae67d3b7e44a0d1e3cd332aa471dc.0
Glide对文件缓存时, 采用SHA-256加密算法, 所以如果需要获得图片, 需要将获得的文件copy一份, 命名为图片格式的文件.
对应代码:
/**
* oldPath: 图片缓存的路径
* newPath: 图片缓存copy的路径
*/
public static void copyFile(String oldPath, String newPath) {
try {
int byteRead;
File oldFile = new File(oldPath);
if (oldFile.exists()) {
InputStream inStream = new FileInputStream(oldPath);
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1024];
while ( (byteRead = inStream.read(buffer)) != -1) {
fs.write(buffer, 0, byteRead);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("复制文件操作出错");
e.printStackTrace();
}
}
这样就会在新的路径下生成所需要的图片文件. 通过这种方式就可以获取Glide的磁盘缓存.