How Image Loading Libraries work in Android?

By | July 14, 2018

In this article, Lets find out how the image loading libraries like Picasso, Glide and Fresco works.

We know that images are the one which takes most of the space in our application either in App size or
the memory at runtime.

Also using large number of images often kicks off Garbage Collection (GC) Events.
The more number of GCs, the more your application is going to suffer.
Remember that when the GC is running, your application is not running, resulting in frame drops and
ultimately bad experience to the user.

Lets look at the problems while loading images and the solutions to solve it.

1. Out of Memory Error

This is the nightmare of Android Developers. The best solution is to load images based on the need.
Scale the images to what you need. All popular libraries scale the image to the image dimensions.
So when you scale the image, it takes lesser memory and no OOM error.

2. Threading

All popular libraries use threading mechanism to download and process bitmaps. They use ThreadPools to manage threads.
So they will have a pool of threads that gets reused every time. In that the threads will be reused and when done they are released to the pool.
If the ImageView is not visible to the user, then the thread gets cancelled and released to the pool. The pools will have size depending on the hardware
configuration of the device. So this approach will perform better on different spec devices.

3. Caching

This is one of the most important part of the library. The image downloaded are cached in the memory or in the disk. They will first check for
memory cache to load the image, if it is not present in the image cache, it checks for the disk cache, if the image is not present in the disk
cache, then the downloads starts from the internet.

4. Bitmap Reuse

The image loading libraries use a pool of Bitmaps. These gets used until the pool is full. The second thing is use of Bitmap that is released.
When a bitmap is ready for recycle, then it is pushed to the pool.
There is another option to reuse the Bitmap memory.
Use of inBitmap in Bitmap options helps reuse of the old bitmap.

Lets look at an example

   Bitmap bitmapOne = BitmapFactory.decodeFile(filePathOne);

   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeFile(filePathTwo, options);
   options.inMutable = true;
   options.inBitmap = bitmapOne;
   options.inJustDecodeBounds = false;
   Bitmap bitmapTwo = BitmapFactory.decodeFile(filePathTwo, options);

Reuse of memory and reusing the reference helps GC not to be triggered.

However inBitmap has some limitations.
Have a look at the below video for more information.

One thought on “How Image Loading Libraries work in Android?

  1. Pingback: Things to Know About Mobile UX – CODERZHEAVEN

Leave a Reply

Your email address will not be published. Required fields are marked *