Search code examples
androidperformanceandroid-imageimage-scaling

How to speed up loading images as small previews?


I have 3 or 4 image paths that I use to load an image so I set it to an imageview. Why does it take long? Or better asking is there a way to make it faster? At the end of the day I am loading to fit an imageview of less than 60 dp hight and width

Uri mainImgeUri = Uri.parse(imagePath);
InputStream imageStream;
try {
    imageStream = mActiviy.getContentResolver().openInputStream(mainImgeUri);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 8;
    Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream, null, options);
    mainImageIV.setImageBitmap(yourSelectedImage);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

USE CASE: What happens is that a user will add 5 images (and he get to choose them from Gallery which is mostly taken by phone camera). He hit save and my app stores the path to them in an sqlite database. Then when the user opens the app again to see them, my app query the db to get the paths to all the images and executes the code above x number of times so all the image views are loaded with the intended images


Solution

  • Take a look at http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

    It explains how to calculate the correct inSampleSize based on the required dimensions of the output image. It also explains how to reference large bitmaps without having to load all their pixel data into memory.

    The idea is that you resample bigger images and only load the smaller ones into memory making the whole process much more efficient. The example code is accessing a bitmap from resources, but this can easily be modified for your needs.

    The important things to look out for in the example are inJustDecodeBounds and calculateInSampleSize.