Skip to content

Instantly share code, notes, and snippets.

@Tarelochkin
Created August 18, 2017 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tarelochkin/00ac73859c6102e2fa12c4ced04af3a2 to your computer and use it in GitHub Desktop.
Save Tarelochkin/00ac73859c6102e2fa12c4ced04af3a2 to your computer and use it in GitHub Desktop.
Resize Bitmap according to the maximum allowed size (width or height) in dp
public final class BitmapUtility {
private BitmapUtility() {
}
// scale the bitmap for a given maximum dimension
// (width or height depending on the image's aspect ratio)
public static Bitmap scaleBitmap(Bitmap bitmap, int dp, Context context) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int bounding = dpToPx(dp, context);
// Determine how much to scale: the dimension requiring less scaling is
// closer to the its side. This way the image always stays inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) bounding) / width;
float yScale = ((float) bounding) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
}
// convert from device-dependent density pixels to raw pixels
private static int dpToPx(int dp, Context context) {
float density = context.getResources().getDisplayMetrics().density;
return Math.round((float) dp * density);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment