Created
October 10, 2015 09:24
-
-
Save fabdarice/224046f61cabf303b87a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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