Creating a scaled bitmap with createScaledBitmap in Android

android, bitmap, java

Solution

If you already have the original bitmap in memory, you don't need to do the whole process of `inJustDecodeBounds`, `inSampleSize`, etc. You just need to figure out what ratio to use and scale accordingly.

final int maxSize = 960;
int outWidth;
int outHeight;
int inWidth = myBitmap.getWidth();
int inHeight = myBitmap.getHeight();
if(inWidth > inHeight){
    outWidth = maxSize;
    outHeight = (inHeight * maxSize) / inWidth; 
} else {
    outHeight = maxSize;
    outWidth = (inWidth * maxSize) / inHeight; 
}

Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, outWidth, outHeight, false);

If the only use for this image is a scaled version, you're better off using Tobiel's answer, to minimize memory usage.

Problem

I want to create a scaled bitmap, but I seemingly get a dis-proportional image. It looks like a square while I want to be rectangular. My code: ``` Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, 960, 960, false); ``` I want the image to have a MAX of 960. How would I do that? Setting width to `null` doesn't compile. It's probably simple, but I can't wrap my head around it. Thanks

Original source

Related problems