根据ImageView的大小来压缩Bitmap,避免OOM

来源:互联网 发布:投资经理 知乎 编辑:程序博客网 时间:2024/04/29 21:43

转载自:http://www.cnblogs.com/tianzhijiexian/p/4254110.html

Bitmap是引起OOM的罪魁祸首之一,当我们从网络上下载图片的时候无法知道网络图片的准确大小,所以为了节约内存,一般会在服务器上缓存一个缩略图,提升下载速度。除此之外,我们还可以在本地显示图片前将图片进行压缩,使其完全符合imageview的大小,这样就不会浪费内存了。

一、思路

思路:计算出要显示bitmap的imageview大小,根据imageview的大小压缩bitmap,最终让bitmap和imageview一样大。

 

二、获得ImageView的宽高

int android.view.View.getWidth() // 返回:The width of your view, in pixels. 
int android.view.View.getWidth() // 返回:The height of your view, in pixels. 

通过这两个方法我就能得到imageview实际的大小了,单位是pix。这个方法请在imageview加载完毕后再调用,否则一致返回空。如果你不知道什么时候会加载完毕,你可以将其放入view.post方法中。

复制代码
       view.post(new Runnable() {                                @Override                public void run() {                    // TODO 自动生成的方法存根                }            })
复制代码

 

三、通过BitmapFactory得到压缩后的bitmap

3.1 BitmapFactory.Options

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

  • SD卡中的图片可以使用decodeFile方法:Bitmap android.graphics.BitmapFactory.decodeFile(String pathName,Options opts)
  • 网络上的图片可以使用decodeStream方法:Bitmap android.graphics.BitmapFactory.decodeResource(Resources res, int id, Options opts)
  • 资源文件中的图片可以使用decodeResource方法:Bitmapandroid.graphics.BitmapFactory.decodeResource(Resources res, int id, Options opts)

这些方法都会为一个bitmap分配内存,如果你的图片太大就很容易造成bitmap。为此,这里面都可以传入一个BitmapFactory.Options对象,用来进行配置。

BitmapFactory.Options options = new BitmapFactory.Options();

BitmapFactory.Options中有个inJustDecodeBounds属性,这个属性为true时,调用上面三个方法返回的就不是一个完整的bitmap对象,而是null。这是因为它禁止这些方法为bitmap分配内存。那么它有什么用呢?设置inJustDecodeBounds=true后,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;
复制代码

 

3.2 初步计算压缩比率

BitmapFactory.Options中有个inSampleSize属性,可以理解为压缩比率。设定好压缩比率后,调用上面的decodexxxx()就能得到一个缩略图了。比如inSampleSize=4,载入的缩略图是原图大小的1/4。

为了避免OOM异常,最好在解析每张图片的时候都先检查一下图片的大小,以下几个因素是我们需要考虑的:

  • 预估一下加载整张图片所需占用的内存

  • 为了加载这一张图片你所愿意提供多少内存

  • 用于展示这张图片的控件的实际大小

  • 当前设备的屏幕尺寸和分辨率

比如,你的ImageView只有128*96像素的大小,只是为了显示一张缩略图,这时候把一张1024*768像素的图片完全加载到内存中显然是不值得的。比如我们有一张2048*1536像素的图片,将inSampleSize的值设置为4,就可以把这张图片压缩成512*384像素。原本加载这张图片需要占用13M的内存,压缩后就只需要占用0.75M了(假设图片是ARGB_8888类型,即每个像素点占用4个字节)。

同理,假设原图是1500x700的,我们给缩略图留出的空间是100x100的。那么inSampleSize=min(1500/100, 700/100)=7。我们可以得到的缩略图是原图的1/7。

下面的代码可以用来计算这个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;}
复制代码

然而,事实不如我们现象的那么美好。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. 

即使设置了inSampleSize=7,但是得到的缩略图却是原图的1/4,原因是inSampleSize只能是2的整数次幂,如果不是的话,向下取得最大的2的整数次幂,7向下寻找2的整数次幂,就是4。这样设计的原因很可能是为了渐变bitmap压缩,毕竟按照2的次方进行压缩会比较高效和方便。

 

3.3 再次计算压缩比率

通过上面的分析我们知道,bitmap是可以被压缩的,我们可以根据需要来压缩bitmap,但压缩得到的bitmap可能会比我需要的大。因此,还得改进方法!然后我们发现了Bitmap中的这个方法:

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

createScaledBitmap()可以给我们一个按照要求拉伸/缩小后的bitmap,我们可以通过这个方法把我们之前得到的较大的缩略图进行缩小,让其完全符合实际显示的大小。好了,现在我们开始写代码:

复制代码
    /**     * @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) {
   // 如果是放大图片,filter决定是否平滑,如果是缩小图片,filter无影响,我们这里是缩小图片,所以直接设置为false Bitmap dst = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, false); if (src != dst) { // 如果没有缩放,那么不回收 src.recycle(); // 释放Bitmap的native像素数组 } return dst; }
复制代码

现在我们就完成了如下的四个过程。

1. 使用inJustDecodeBounds,仅仅读bitmap的长和宽。
2. 根据bitmap的长款和目标缩略图的长和宽,计算出inSampleSize的大小。
3. 使用inSampleSize,载入一个比imageview大一点的缩略图A
4. 使用createScaseBitmap再次压缩A,将缩略图A生成我们需要的缩略图B。
5. 回收缩略图A(如果A和B的比率一样,就不回收A)。

  有朋友问,为啥要先从inSampleSize产生一个缩略图A,而不是直接把原始的bitmap通过createScaseBitmap()缩放为目标图片呢?

因为如果要从原始的bitmap直接进行缩放的话,就需要将原始图片放入内存中,十分危险!!!现在通过计算得到一个缩略图A,这个缩略图A比原图可以小了很多,完全可以直接加载到内存中,这样再进行拉伸就比较安全了。

 

四、产生工具类

现在已经把所有的技术难点攻克了,完全可以写一个工具类来产生缩略图。工具类中应该包含生成缩略图的重要方法:

复制代码
    /**     * @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); // 通过得到的bitmap进一步产生目标大小的缩略图    }    /**     * @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);    }
复制代码

这两个方法的过程完全一致,产生一个option对象,设置inJustDecodeBounds参数,开始第一次解析bitmap,获得bitmap的宽高数据,然后通过宽高数据计算缩略图的比率。得到缩略图比率后,我们把inJustDecodeBounds设置为false,开始正式解析bitmap,最终得到的是一个可能比想要的缩略图略大的bitmap。最后一部是检查bitmap是否是我们想要的bitmap,如果是就返回,不是的话就开始拉伸,总之最终会返回一个完全符合imageview大小的bitmap,不浪费一点点内存。

 

完整的工具类代码如下:

复制代码
package com.kale.bitmaptest;import android.content.res.Resources;import android.graphics.Bitmap;import android.graphics.BitmapFactory;/** * @author:Jack Tony * @description  : * @web : * http://developer.android.com/training/displaying-bitmaps/load-bitmap.html * http://www.cnblogs.com/kobe8/p/3877125.html *  * @date  :2015年1月27日 */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;            // Calculate the largest inSampleSize value that is a power of 2 and keeps both            // height and width larger than the requested height and width.            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) {
     // 如果是放大图片,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); // 通过得到的bitmap,进一步得到目标大小的缩略图 } /** * @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); }}
复制代码

 

五、测试

我在布局中建立一个100x100dp的imageview,然后在res中放一张图片。

5.1 布局文件

放入两个按钮,一个按钮启动的是用常规的方法加载bitmap,不压缩;另一个启动压缩算法。

复制代码
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:padding="16dp"    tools:context="${relativePackage}.${activityClass}" >    <TextView        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Bitmap Test" />    <ImageView        android:id="@+id/imageView"        android:layout_width="100dp"        android:layout_height="100dp"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:scaleType="fitXY"        android:src="@drawable/ic_launcher" />    <Button        android:id="@+id/original_button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:onClick="butonListener"        android:text="加载原图" />    <Button        android:id="@+id/clip_button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignBaseline="@+id/original_button"        android:layout_alignBottom="@+id/original_button"        android:layout_alignParentRight="true"        android:onClick="butonListener"        android:text="加载缩略图" /></RelativeLayout>
复制代码

 

5.2 java代码

复制代码
    public void butonListener(View v) {        switch (v.getId()) {        case R.id.original_button:            loadBitmap(false); // 加载原图            break;        case R.id.clip_button:            loadBitmap(true); // 加载缩略图            break;        }    }    public void loadBitmap(boolean exactable) {        int bmSize = 0;        Bitmap bm = null;        if (exactable) {            // 通过工具类来产生一个符合ImageView的缩略图,因为ImageView的大小是50x50,所以这里得到的缩略图也应该是一样大小的            bm = BitmapUtils.decodeSampledBitmapFromResource(getResources(), R.drawable.saber, iv.getWidth(), iv.getHeight());        } else {            // 直接加载原图            bm = BitmapFactory.decodeResource(getResources(), R.drawable.saber);        }        iv.setImageBitmap(bm);        bmSize += bm.getByteCount(); // 得到bitmap的大小        int kb = bmSize / 1024;        int mb = kb / 1024;        Toast.makeText(this, "bitmap size = " + mb + "MB" + kb + "KB", Toast.LENGTH_LONG).show();    }
复制代码

根据点击不同的按钮,触发不同的方法,最终把得到的bitmap放入imageview,并且显示当前的bitmap大小。运行后可以发现,经过压缩算法得到的bitmap要小很多,更加节约内存。

结果:原图:1M+;缩略图:156kb。

注意:当你的imageview远远小于bitmap原图大小的时候这种压缩算法十分有效,但是如果的bitmap和imageview大小差不多,你会发现这个算法的作用就不那么明显了,而且不要认为用了压缩就永远不会出现OOM了。

PS:实际使用中我们的bitmap经常是大于imageview的,所以推荐采用此方法。

0 0
原创粉丝点击