Skip to content

Instantly share code, notes, and snippets.

@fabdarice
Created October 10, 2015 09:24
Show Gist options
  • Save fabdarice/224046f61cabf303b87a to your computer and use it in GitHub Desktop.
Save fabdarice/224046f61cabf303b87a to your computer and use it in GitHub Desktop.
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth) {
// 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);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth) {
final int width = options.outWidth;
int inSampleSize = 1;
if (width > reqWidth) {
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 (halfWidth / inSampleSize) > reqWidth {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment