Skip to content

Instantly share code, notes, and snippets.

@duanhong169
Last active December 15, 2015 08:59
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 duanhong169/5235259 to your computer and use it in GitHub Desktop.
Save duanhong169/5235259 to your computer and use it in GitHub Desktop.
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// 从BitmapFactory.Options中获取图片的原始高度和宽度
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// 计算原始尺寸与显示尺寸的比例
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// 使用两个比例中较小的作为采样比,可以保证图片在两个方向上都满足需求
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// 为了防止一些纵横比异常(很宽或者很长)的图片仍然会占用较大内存,增加
// 对显示像素的限制
final float totalPixels = width * height;
// 如果以前面计算到的采样比采样得到的bitmap像素大于请求的像素的两倍,继续
// 提高采样比
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment