Skip to content

Instantly share code, notes, and snippets.

@javiergamarra
Created May 22, 2015 21:37
Show Gist options
  • Save javiergamarra/beba9320a8eb98f94fa8 to your computer and use it in GitHub Desktop.
Save javiergamarra/beba9320a8eb98f94fa8 to your computer and use it in GitHub Desktop.
Classic code for resizing an image
public static byte[] decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayBitmapStream);
return byteArrayBitmapStream.toByteArray();
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
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