glide是加载图片框架,同时也支持下载图片的功能,这里主要讲解下载的实现:
1.downloadOnly方法,同步下载,需要自己创建线程来执行下载过程
File file = Glide.with(context)
.load(url)
.downloadOnly(width, height)
.get();
下载文件到缓存路径,/data/data/包名/image_manager_disk_cache 这样的路径,可以将缓存文件复制到需要的地方,例如sdcard中。width,height是下载的图片宽和高,不过在改变尺寸后仍然下载的是原图,没有按照预期的宽高返回,个人认为是get()函数不支持预定义宽高。
项目中使用的实例:
private inner class getImageCacheAsyncTask(private val context: Context) : AsyncTask<String, Void, File>() {
override fun doInBackground(vararg params: String): File? {
val imgUrl = params[0]
try {
return Glide.with(context)
.load(imgUrl)
.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get()
} catch (ex: Exception) {
return null
}
}
override fun onPostExecute(result: File?) {
if (result == null) {
return
}
val path = result.path
Log.e("path", path)
bitmap = BitmapFactory.decodeFile(path)
// copyView.setImageBitmap(bmp)
}
}
2.asBitmap()方法,同步下载,直接下载图片加载到Bitmap中。
Bitmap bitmap = Glide.with(context)
.load(url)
.asBitmap()
.into(width, height)
.get();
3.asBitmap().toBytes() 有些情况需要保存获取到的自定义大小图片,可以使用toBytes()函数。
byte[] bytes = Glide.with(context)
.load(url)
.asBitmap()
.toBytes()
.into(width, height)
.get();
4.SimpleTarget,异步下载,前面几个方法需要在线程中执行,否则会阻塞主线程,通过SimpleTarget是先异步下载
Glide通过SimpleTarget类实现异步下载,所以必须在主线程中使用,在其他线程调用会出现异常,SimpleTarget可以为多种类型,通过前面的asBitmap().toBytes()函数控制,width和height是图片自定义加载的宽高。
Glide.with(context)
.load(url)
.asBitmap()
.toBytes()
.into(new SimpleTarget<byte[]>(width, height) {
@Override
public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
// 下载成功回调函数
// 数据处理方法,保存bytes到文件
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
// 下载失败回调
}
});