使用BitmapFactory压缩图片大小

来源:互联网 发布:淘宝号一天刷几单安全 编辑:程序博客网 时间:2024/05/19 05:40

概要说明:

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 int inSampleSize

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);

1 0
原创粉丝点击