BitmapFactory压缩图片

来源:互联网 发布:sql check约束表达式 编辑:程序博客网 时间:2024/06/05 16:02
       我们编写的应用程序都是有一定内存限制的,程序占用了过高的内存就容易出现OOM(OutOfMemory)异常。所以在展示高分辨率图片或者上传图片的时候,最好先将图片进行压缩。下面看下我们如何对一张大图进行适当的压缩,让它能够以最佳大小显示的同时,还能防止OOM的出现。

      BitmapFactory是一个工具类,提供了多个解析方法(decodeByteArray, decodeFile, decodeResource等)用于创建Bitmap对象,我们应该根据图片的来源选择合适的方法。

  • SD卡中的图片可以使用decodeFile方法: Bitmap android.graphics.BitmapFactory.decodeFile(String pathName,Options opts)
  • 网络上的图片可以使用decodeStream方法: Bitmap android.graphics.BitmapFactory.decodeStream(InputStream is)
  • 资源文件中的图片可以使用decodeResource方法: Bitmap android.graphics.BitmapFactory.decodeResource(Resources res, int id,Options opts)
       这些方法会尝试为已经构建的bitmap分配内存,如果你的图片太大就会很容易造成OOM。为此每一种解析方法都提供了一个可选的BitmapFactory.Options参数,将这个参数的inJustDecodeBounds属性设置为 true就可以让解析方法禁止为bitmap分配内存,返回值也不再是一个Bitmap对象,而是null。虽然Bitmap是null了,但是 BitmapFactory.Options的outWidth、outHeight和outMimeType属性都会被赋值。这让我们可以在加载图片之前就获取到图片的长宽值和MIME类型,从而根据情况对图片进行压缩。如下:
    BitmapFactory.Options options = new BitmapFactory.Options();      options.inJustDecodeBounds = true;      BitmapFactory.decodeResource(getResources(), R.id.myimage, options);      int imageHeight = options.outHeight;      int imageWidth = options.outWidth;      String imageType = options.outMimeType;  
       BitmapFactory.Options中有个inSampleSize属性,可以理解为压缩比率。设定好压缩比率后,调用上面的decodexxxx()就能得到一个缩略图了。比如我们有一张2048*1536像素的图片,将inSampleSize的值设置为4,就可以把这张图片压缩成512*384像素。原本加载这张图片需 要占用13M的内存,压缩后就只需要占用0.75M了(假设图片是ARGB_8888类型,即每个像素点占用4个字节)。下面的方法可以根据传入的宽和高,计算出合适的inSampleSize值:
    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.Options的inJustDecodeBounds属性设置为true,解析一次图片。然后将 BitmapFactory.Options连同期望的宽度和高度一起传递到到calculateInSampleSize方法中,就可以得到合适的 inSampleSize值了。之后再解析一次图片,使用新获取到的inSampleSize值,并把inJustDecodeBounds设置为 false,就可以得到压缩后的图片了。
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,              int reqWidth, int reqHeight) {          // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小          final BitmapFactory.Options options = new BitmapFactory.Options();          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);      }  

      然而,文档中inSampleSize的注释中有一个需要注意的一点。下面是原注释:

      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. 

任何其他值将向下取得最大的2的整数次幂。比如inSampleSize=5或6或7,将取为4。

这样Bitmap是可以被压缩,只是压缩得到的Bitmap可能会比我们需要的大。需要怎么才能更好的压缩呢?Bitmap中还有一个方法:

Bitmap android.graphics.Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)

       createScaledBitmap()可以给我们一个按照要求拉伸/缩小后的Bitmap,我们可以通过这个方法把我们之前得到的较大的缩略图进行缩小,使其完全符合我们的要求。

       现在我们写一个工具类,完成了如下过程:

  1.  将inJustDecodeBounds设为true,
  2. 调用decodexxxx()方法,读取图片长宽。 
  3. 计算出inSampleSize的大小。
  4.  将inJustDecodeBounds设为false。
  5. 调用decodexxxx()方法得到一个可能大一点的缩略图A。 
  6. 使用createScaseBitmap再次压缩A,将缩略图A生成我们需要的缩略图B。
  7. 回收缩略图A(如果A和B的比率一样,就不回收A)。

/** * 用于压缩图片 * Created by lyh on 2016/2/3 0017. */public class BitmapUtils {    /**     * @description 计算图片的压缩比率     *     * @param options 参数     * @param reqWidth 目标的宽度     * @param reqHeight 目标的高度     * @return     */    private 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 halfHeight = height / 2;            final int halfWidth = width / 2;            while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {                inSampleSize *= 2;            }        }        return inSampleSize;    }    /**     * @description 通过传入的bitmap,进行压缩,得到符合标准的bitmap     *     * @param src     * @param dstWidth     * @param dstHeight     * @return     */    private static Bitmap createScaleBitmap(Bitmap src, int dstWidth, int dstHeight, int inSampleSize) {        //如果inSampleSize是2的倍数,也就说这个src已经是我们想要的缩略图了,直接返回即可。        if (inSampleSize % 2 == 0) {            return src;        }        // 如果是放大图片,filter决定是否平滑,如果是缩小图片,filter无影响,我们这里是缩小图片,所以直接设置为false        Bitmap dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false);        if (src != dst) { // 如果没有缩放,那么不回收            src.recycle(); // 释放Bitmap的native像素数组        }        return dst;    }    /**     * @description 从Resources中加载图片     *     * @param res     * @param resId     * @param reqWidth     * @param reqHeight     * @return     */    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {        final BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true; // 设置成了true,不占用内存,只获取bitmap宽高        BitmapFactory.decodeResource(res, resId, options); // 读取图片长宽        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 调用上面定义的方法计算inSampleSize值        // 使用获取到的inSampleSize值再次解析图片        options.inJustDecodeBounds = false;        Bitmap src = BitmapFactory.decodeResource(res, resId, options); // 载入一个稍大的缩略图        return createScaleBitmap(src, reqWidth, reqHeight, options.inSampleSize); // 进一步得到目标大小的缩略图    }    /**     * @description 从SD卡上加载图片     *     * @param pathName     * @param reqWidth     * @param reqHeight     * @return     */    public static Bitmap decodeSampledBitmapFromFile(String pathName, int reqWidth, int reqHeight) {        final BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true;        BitmapFactory.decodeFile(pathName, options);        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);        options.inJustDecodeBounds = false;        Bitmap src = BitmapFactory.decodeFile(pathName, options);        return createScaleBitmap(src, reqWidth, reqHeight, options.inSampleSize);    }}

      下面的代码非常简单地将任意一张图片压缩成100*100的缩略图,并在ImageView上展示。
mImageView.setImageBitmap( BitmapUtils.decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

参考自:
http://blog.csdn.net/guolin_blog/article/details/9316683
http://developer.android.com/intl/zh-cn/training/displaying-bitmaps/index.html

0 0
原创粉丝点击