尽量避免因图片(Bitamp)过大而导致内存溢出 工具类

</pre><pre name="code" class="java">public class ImageUtile {
	
	/**
	 * 将资源图片按照需要显示的大小进行合理压缩,防止程序因图片过大引起的内存溢出,导致程序崩溃
	 * @param res Resources
	 * @param resId 资源ID
	 * @param reqWidth 需要显示的宽度
	 * @param reqHeight 需要显示的高度
	 * @return 经过合理压缩后的位图(Bitmap)
	 */
	public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { 
      // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小 
      final BitmapFactory.Options options = new BitmapFactory.Options(); 
      //将这个参数的inJustDecodeBounds属性设置为true
      //就可以让解析方法禁止为bitmap分配内存,返回值也不再是一个Bitmap对象,而是 null
      options.inJustDecodeBounds = true; 
      BitmapFactory.decodeResource(res, resId, options); 
      // 计算inSampleSize值 
      options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 
      // 使用获取到的inSampleSize值再次解析图片 
      options.inJustDecodeBounds = false; 
      return BitmapFactory.decodeResource(res, resId, options); 
	}
	
	/**
	 * 计算压缩比
	 * @param options 图片加载配置参数
	 * @param reqWidth 需要显示的宽度
	 * @param reqHeight 需要显示的高度
	 * @return 压缩比
	 */
	public static int calculateInSampleSize(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 heightRatio = Math.round((float) height / (float) reqHeight); 
	      final int widthRatio = Math.round((float) width / (float) reqWidth); 
	      // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高 
	      // 一定都会大于等于目标的宽和高。 
	      inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; 
      } 
      return inSampleSize; 
	}
}


当然,加载文件图片、流图片等都可以应用此方法,只需要更改BitmapFactory.decodeResource——>BitmapFactory.decodeFile(pathName, opts)等,就可以了

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值