使用BitmapFactory压缩图片大小

概要说明:

1、所谓解析图片就是将图片源文件加载为Bitmap对象;

2、解析,我们主要使用BitmapFactory的decodeFile方法;但是我们可以通过BitmapFactory.Options来调整decodeFile方法的具体行为(或者纯粹获取图片尺寸或者压缩图片

压缩过程:

1、获取图片尺寸
概述:将inJustDecodeBounds设置为true,decodeFile()后就可以通过options.outWidth等获取图片尺寸
		/**
		 * 第一轮解释,只为获取图片大小
		 */
		// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(pathName, options);
		// 源图片的宽度
		final int width = options.outWidth;

2、计算缩小比例
(概述:我们需要计算出缩小比例inSampleSize)
所谓的inSampleSize就是,我们最后得到目标图片大小为源图片除以inSampleSize后的大小。关于,这个变量的具体含义,可以参考下面的官方文档说明:
public intinSampleSize
Added in API level 1

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1. Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.

以下是计算缩小比例的示例:
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth) {
		// 源图片的宽度
		final int width = options.outWidth;
		int inSampleSize = 1;
		if (width > reqWidth) {
			// 计算出实际宽度和目标宽度的比率
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = widthRatio;
		}
		return inSampleSize;
	}

3、设定 缩小比例,并且使用这个缩小比例对图片进行缩小处理
(注意:需要重新将inJustDecodeBounds 设定为false)
示例代码如下:
// 调用上面定义的方法计算inSampleSize值(inSampleSize值为图片压缩比例)
		options.inSampleSize = calculateInSampleSize(options, reqWidth);
		/**
		 * 第二轮解析,负责具体压缩
		 */
		// 使用获取到的inSampleSize值再次解析图片
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(pathName, options);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值