Skip to content

Instantly share code, notes, and snippets.

@AizazZaidee
Last active August 29, 2015 14:08
Show Gist options
  • Save AizazZaidee/d00a25bc75a935ce69c3 to your computer and use it in GitHub Desktop.
Save AizazZaidee/d00a25bc75a935ce69c3 to your computer and use it in GitHub Desktop.
Resize a bitmap with given width and height code snippet.
public static Bitmap getImageThumbnail(final String pPath, final int pWidth, final int pHeight) {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pPath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, pWidth, pHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(pPath, options);
}
private 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment