Skip to content

Instantly share code, notes, and snippets.

@nesquena
Created March 5, 2014 07:17
Show Gist options
  • Save nesquena/3885707fd3773c09f1bb to your computer and use it in GitHub Desktop.
Save nesquena/3885707fd3773c09f1bb to your computer and use it in GitHub Desktop.
Easy utility for scaling bitmaps
public class BitmapScaler
{
// scale and keep aspect ratio
public static Bitmap scaleToFitWidth(Bitmap b, int width)
{
float factor = width / (float) b.getWidth();
return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
}
// scale and keep aspect ratio
public static Bitmap scaleToFitHeight(Bitmap b, int height)
{
float factor = height / (float) b.getHeight();
return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
}
// scale and keep aspect ratio
public static Bitmap scaleToFill(Bitmap b, int width, int height)
{
float factorH = height / (float) b.getWidth();
float factorW = width / (float) b.getWidth();
float factorToUse = (factorH > factorW) ? factorW : factorH;
return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorToUse),
(int) (b.getHeight() * factorToUse), true);
}
// scale and don't keep aspect ratio
public static Bitmap strechToFill(Bitmap b, int width, int height)
{
float factorH = height / (float) b.getHeight();
float factorW = width / (float) b.getWidth();
return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorW),
(int) (b.getHeight() * factorH), true);
}
}
@goofyahead
Copy link

Its just a typo but since this gist is referenced in codepath for android should be updated :)

float factorH = height / (float) b.getWidth();

In method scaleToFill(Bitmap b, int width, int height) should be:

float factorH = height / (float) b.getHeight();

Now bitmaps will be resized in their largest side! Thanks for the gist anyway 👍

@AndroidDeveloperLB
Copy link

Is there something similar to center-crop, yet I have the choice where to focus in terms of specific point/rectangle in the bitmap?
I want to make sure a specific point/rectangle is shown while fitting&cropping.
How can I do it?
Currently the only similar thing that exists officially for ImageView is center-crop, but it's only to the center. What if the most important part in the image is at the bottom, instead? Or 10% (or 10px) from the bottom, etc... ? Or if there is a specific region in the bitmap that's most important?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment