1、所谓解析图片就是将图片源文件加载为Bitmap对象;
2、解析,我们主要使用BitmapFactory的decodeFile方法;但是我们可以通过BitmapFactory.Options来调整decodeFile方法的具体行为(或者纯粹获取图片尺寸;或者压缩图片)
/** * 第一轮解释,只为获取图片大小 */ // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小 final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(pathName, options); // 源图片的宽度 final int width = options.outWidth;
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; }
// 调用上面定义的方法计算inSampleSize值(inSampleSize值为图片压缩比例) options.inSampleSize = calculateInSampleSize(options, reqWidth); /** * 第二轮解析,负责具体压缩 */ // 使用获取到的inSampleSize值再次解析图片 options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(pathName, options);
使用BitmapFactory压缩图片大小,布布扣,bubuko.com
原文:http://blog.csdn.net/kaiwii/article/details/21704659