Skip to content

Instantly share code, notes, and snippets.

@atermenji
Created November 30, 2012 09:21
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 atermenji/4174718 to your computer and use it in GitHub Desktop.
Save atermenji/4174718 to your computer and use it in GitHub Desktop.
BitmapFactory.Options inSampleSize calculating
public static int calculateInSampleSizeInside(BitmapFactory.Options options, int maxWidth, int maxHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > maxHeight || width > maxWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) maxHeight);
} else {
inSampleSize = Math.round((float) width / (float) maxWidth);
}
if (height < maxHeight && width > maxWidth) {
inSampleSize = Math.round((float) width / (float) maxWidth);
}
if (height > maxHeight && width < maxWidth) {
inSampleSize = Math.round((float) height / (float) maxHeight);
}
if (inSampleSize == 1) {
inSampleSize += 1;
}
}
return inSampleSize;
}
@nagygabor
Copy link

This doesnt work well, pic could be bigger than maxWidth/maxHeight

Math.ceil should apply

@nagygabor
Copy link

Works better:

//http://madhusudhanrc.blogspot.hu/2012/09/reduce-bitmap-size-using.html
public static int calculateInSampleSizeInside(int width, int height, int maxWidth, int maxHeight) {
    int inSampleSize = 1;

    int heightRatio = (int)Math.ceil((float)height/(float)maxHeight);
    int widthRatio = (int)Math.ceil((float)width/(float)maxWidth);

    if (heightRatio > 1 || widthRatio > 1)
    {
        if (heightRatio > widthRatio)
        {
            inSampleSize = heightRatio;
        } else {
            inSampleSize = widthRatio;
        }
    }
    return inSampleSize;
}

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