How to Apply Loading Large Bitmaps Efficiently

Asked

Viewed 73 times

0

I am using Imageview to upload images because I find lack of memory error found this method, because I am not able to use. wanted a brief explanation where I change the variables

available in http://developer.android.com/training/displaying-bitmaps/load-bitmap.html#load-bitmap

Read Bitmap Dimensions and Type

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;

Put a reduced version in Memory

  public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

    final int halfHeight = height / 2;
    final int halfWidth = width / 2;

    // Calculate the largest inSampleSize value that is a power of 2 and keeps both
    // height and width larger than the requested height and width.
    while ((halfHeight / inSampleSize) > reqHeight
            && (halfWidth / inSampleSize) > reqWidth) {
        inSampleSize *= 2;
    }
}

return inSampleSize;
}

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId 
      int reqWidth, int reqHeight) {

// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}

1 answer

1


Use a AsyncTask to perform the calculation of the images, avoiding the Main Thread get stuck!

Another tip is you use Composites to render these images, i.e., ListView, GridView, RecyclerView, etc, because this way it will only load in memory the images that are being displayed to the user.

  • Take a look at this library too, it will help you A LOT! https://github.com/square/picasso

Browser other questions tagged

You are not signed in. Login or sign up in order to post.