When high resolution images are loaded in low resolution or lower dpi devices application crashes due to the limited memory. Here, I have written steps for sub sampling images to the efficient sub sampling ratio.
1) Reading resources using memory efficient bitmaps:
public Bitmap decodeResourceToBitmap(@DrawableRes int id) throws Exception {
try {
return BitmapFactory.decodeResource(mContext.getResources(), id, mOptions);
} catch (OutOfMemoryError oom) {
if (mDownSamplingAttempts < MAX_DOWNSAMPLING_ATTEMPTS) {
// Increase our sampling by a factor of 2
mOptions.inSampleSize *= 2;
mDownSamplingAttempts++;
}
}
throw new Exception("Failed to load resource ID: " + id);
}
2) Calculate subsampling ratio for efficient loading of memory
public int calculateSubSamplingRatioForBitmap(int reqWidth, int reqHeight) {
final int height = mOptions.outHeight;
final int width = mOptions.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;
}
3) Decode resources with to required width and height
public Bitmap decodeSubSamImageToReqWidthHeight(Resources res, @DrawableRes int resId, int reqWidth, int reqHeight) throws Exception {
decodeResourceToBitmap(resId);
BitmapFactory.decodeResource(res, resId, mOptions);
// Calculate inSampleSize
mOptions.inSampleSize = calculateSubSamplingRatioForBitmap(reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
mOptions.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, mOptions);
}
4) Setting resource to view
public void setResourceToImageView(ImageView imageView, @DrawableRes int imageResourceId) throws Exception {
decodeResourceToBitmap(imageResourceId);
imageView.setImageBitmap(decodeSubSamImageToReqWidthHeight(mContext.getResources(), imageResourceId, 100, 100));
}