使用Glide加载图像,同时服务器返回base64。

8
当我通过以下方式加载图像时:

String url = "https://example.com/user/123123/profile_pic" Glide.with(context).load(url).into(imageView);

服务器响应是以 base64 编码的,glide 默认不处理它。 我的当前解决方案是:

使用 retrofit 加载图像 -> 将编码后的图像传递给 glide

在这种情况下,我会失去 glide 的缓存。我想知道是否有一种方法可以使用 glide 发送该请求并处理 base64 响应?
2个回答

6
你可以将Base64字符串转换为字节,然后将该字节加载到Glide中。
byte[] imageByteArray = Base64.decode(imageBytes, Base64.DEFAULT); 
// here imageBytes is base64String

Glide.with(context)
    .load(imageByteArray)
    .asBitmap()
    .into(imageView);

5
问题是我需要在其他地方发出请求,然后将其传递给 Glide。这样就没有缓存等功能了。我正在寻找让 Glide 处理 base64 响应的方法。 - Tomas

2

使用自定义ModelLoader来加载Glide

https://bumptech.github.io/glide/tut/custom-modelloader.html

这是一个解决该问题的好指南。

Base64DataFetcher类中 ->

public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super ByteBuffer> callback) {  

    String base64Section = getBase64SectionOfModel(); 
    // get this from Retrofit or another
    .........
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接