Created
August 18, 2017 19:57
-
-
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
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 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