I'm looking for a solution for the following problem: how to change the size of a Bitmap
to a fixed size (for example 512x128). The aspect ratio of the bitmap content must be preserved.
I think it should be something like this:
create an empty 512x128 bitmap
scale the original bitmap down to fit the 512x128 pixels with keeping the aspect ratio
copy the scaled into the empty bitmap (centered)
What is the simplest way to achieve this?
The reason for all this is, that the GridView
messes the layout up when the aspect ratio of an image differs from the other. Here is a screenshot (all images except the last one have the aspect ratio of 4:1):
screenshot
Press-and-hold the Shift key, grab a corner point, and drag inward to resize the selection area. Because you're holding the Shift key as you scale, the aspect ratio (the same ratio as your original photo) remains exactly the same.
Bitmaps can be resized without experiencing any distortion. Draw programs store images as bitmaps. Marble is not a desirable material for making sculptures because it is not very durable. Sculptors primarily use visual texture in their works.
Try this, calculate the ratio and then rescale.
private Bitmap scaleBitmap(Bitmap bm) {
int width = bm.getWidth();
int height = bm.getHeight();
Log.v("Pictures", "Width and height are " + width + "--" + height);
if (width > height) {
// landscape
float ratio = (float) width / maxWidth;
width = maxWidth;
height = (int)(height / ratio);
} else if (height > width) {
// portrait
float ratio = (float) height / maxHeight;
height = maxHeight;
width = (int)(width / ratio);
} else {
// square
height = maxHeight;
width = maxWidth;
}
Log.v("Pictures", "after scaling Width and height are " + width + "--" + height);
bm = Bitmap.createScaledBitmap(bm, width, height, true);
return bm;
}
The answer by Coen Damen doesn't always respect Max Height and Max Width. Here's an answer that does:
private static Bitmap resize(Bitmap image, int maxWidth, int maxHeight) {
if (maxHeight > 0 && maxWidth > 0) {
int width = image.getWidth();
int height = image.getHeight();
float ratioBitmap = (float) width / (float) height;
float ratioMax = (float) maxWidth / (float) maxHeight;
int finalWidth = maxWidth;
int finalHeight = maxHeight;
if (ratioMax > 1) {
finalWidth = (int) ((float)maxHeight * ratioBitmap);
} else {
finalHeight = (int) ((float)maxWidth / ratioBitmap);
}
image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
return image;
} else {
return image;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With