Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading image with glide while server returns base64

When I load an image with something like this:

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

server response is in base64 and glide doesn't handle it by default

My current solution:

load image with retrofit -> pass image encoded to glide

in this case I would lose glide caching. I wonder if there is a way to make that request with glide and handle base64 response?

like image 776
Tomas Avatar asked Aug 17 '17 13:08

Tomas


People also ask

Does glide load bitmap or byte array?

imageByteArray successfully converts to bitmap without using glide.

How do you optimize memory consumption when using Glide?

Loading images with the unknown size If a loaded image happens to be smaller than the ImageView, Glide will unnecessarily expand original bitmap to match the size of the target view. One way to prevent it is to set scaleType=”centerInside” in the ImageView. That way loaded image won't expand beyond the original size.

How does Glide cache images?

How does the Glide caching mechanism work? By default, Glide uses memory and disk caching to avoid unnecessary network calls, it checks into multiple layers of caches before initiating a new request call for an image.

Why base64 is needed to transfer images?

Base64 images are primarily used to embed image data within other formats like HTML, CSS, or JSON. By including image data within an HTML document, the browser doesn't need to make an additional web request to fetch the file, since the image is already embedded in the HTML document.


2 Answers

You can convert Base64 String to byte then load that byte into glide.

byte[] imageByteArray = Base64.decode(imageBytes, Base64.DEFAULT); 
// here imageBytes is base64String

Glide.with(context)
    .load(imageByteArray)
    .asBitmap()
    .into(imageView);
like image 168
Chirag Avatar answered Nov 14 '22 23:11

Chirag


Use custom ModelLoader for Glide

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

good manual for this problem

In class Base64DataFetcher ->

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

    String base64Section = getBase64SectionOfModel(); 
    // get this from Retrofit or another
    .........
}
like image 38
Ivan Pursheha Avatar answered Nov 15 '22 00:11

Ivan Pursheha