使用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
- 使用BitmapFactory压缩图片大小
- 使用BitmapFactory压缩图片大小解决android解析图片OOM错误
- 图片压缩--BitmapFactory.Options的使用
- 压缩图片大小
- Android BitmapFactory 图片压缩
- BitmapFactory压缩图片
- bitmapFactory压缩本地图片
- BitmapFactory.Options压缩图片
- 减小网络传输图片大小,使用gzip进行压缩
- java 使用Thumbnailator 上传图片 并压缩图片大小
- 只压缩图片大小
- 在线压缩图片大小
- 压缩图片大小尺寸
- iOS压缩图片大小
- java后台图片大小压缩
- iOS压缩图片大小
- iOS压缩图片大小
- iOS压缩图片大小
- CListCtrl以及其派生类选中项颜色的改变
- 程序人生的规划
- SQL注入
- c++ volatile用法(转)
- talend中的传值
- 使用BitmapFactory压缩图片大小
- 架构师之路(39)---IoC框架 - 王泽宾 - 博客频道 - CSDN.NET
- 2013年蓝桥杯 猜年龄
- Java 8简明教程
- 一道考递归的题目
- 猜数游戏
- 浏览器默认样式表 - 清风小阁 - 博客频道 - CSDN.NET
- FIO 硬盘测试
- 软件测试基础理论杂记一