android 缩略图防止溢出,android imageview 加载大图片防止内存溢出的方法

// width height 实际需要的图片尺寸,为了保证裁剪的图片不变形,最好还是算一下缩放比例,这里就不写了

public static Bitmap loadBitmap(String url, int width, int height)

{

Bitmap bitmap = null;

if (url == null || !new File(url).exists()) return bitmap;

try

{

BitmapFactory.Options opts = new BitmapFactory.Options();

opts.inJustDecodeBounds = true;

BitmapFactory.decodeFile(url, opts);

opts.inSampleSize = calculateSampleSize(opts, width, height);

opts.inJustDecodeBounds = false;

opts.inPreferredConfig = Bitmap.Config.RGB_565;

opts.inPurgeable = true;

opts.inInputShareable = true;

bitmap = BitmapFactory.decodeStream(new FileInputStream(url), null, opts);

bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height);

return bitmap;

}

catch (Exception e)

{

e.printStackTrace();

}

return bitmap;

}

private static int calculateSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)

{

final int height = options.outHeight;

final int width = options.outWidth;

int inSampleSize = 1;

if (height > reqHeight || width > reqWidth)

{

final int halfHeight = height / 2;

final int halfWidth = width / 2;

while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth)

{

inSampleSize *= 2;

}

}

return inSampleSize;

}

sample size就是压缩比例,本质上就是设置恰当的sample size将大的图片尺寸转成相等或略大于我们需要的实际图片尺寸。

inSampleSize*2 是因为官方文档里面提到2的乘方效率最高。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值