Android显示富文本,加载图片过多,内存溢出

最近在做Android的富文本显示时,使用的是底层的html解析类。
在解析图片时,先从服务器端或得图片资源生成bitmap文件,然后将bitmap文件放入Drawable中,返回Drawable。
问题是:
当图片过多时,在使用创建bitmap的createBitmap函数时,造成内存溢出。
请问各位大神,怎么破?应该在什么地方释放内存?怎么释放内存?

你要显示的控件宽高和图片宽高等比压缩


 package neusoft.com.chat.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

import java.io.FileNotFoundException;

/**
 * Created by dell1 on 2017/3/25.
 */
public class BitmapScaleUtils {

    private static BitmapScaleUtils bitmapScaleUtils;
    private Context context;


    private BitmapScaleUtils() {
    }

    private BitmapScaleUtils(Context context) {
        this.context = context;
    }

    public synchronized static BitmapScaleUtils getInstance(Context context) {

        if (bitmapScaleUtils == null) {
            bitmapScaleUtils = new BitmapScaleUtils(context);
        }

        return bitmapScaleUtils;
    }

    public Bitmap getScaleBitmap(Uri imageUri, int targetWidth, int targetHeight) {

        // 创建盒子
        BitmapFactory.Options opts = new BitmapFactory.Options();

        /**
         * 将盒子的opts.inJustDecodeBounds 设置为true 以便于获取图片的宽高信息 而不会真正的将图片加载到内存
         * 只是获取额外的信息
         */
        opts.inJustDecodeBounds = true;
        // 加载图片
        // BitmapFactory.decodeFile(imagePath, opts); 这种方式容易产生 oom
        try {
            BitmapFactory.decodeStream(context.getContentResolver().openInputStream(imageUri), null, opts);
            // 获取图片的宽高
            int width = opts.outWidth;
            int height = opts.outHeight;

            // 求出图片的宽高和手机屏幕的宽高之比
            int widthScale = width / targetWidth;
            int HeightScale = height / targetHeight;

            // 通过三元运算计算出两个比值的大小
            int scale = widthScale > HeightScale ? widthScale : HeightScale;

            // 设置盒子加载图片的比例
            opts.inSampleSize = scale;

            // 将盒子的opts.inJustDecodeBounds设置为false 以便于将图片加载到内存中
            opts.inJustDecodeBounds = false;

            // 在此加载图片 将盒子塞进去
            return BitmapFactory.decodeStream(context.getContentResolver().openInputStream(imageUri), null, opts);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}



将你的图片进行压缩啊

进行压缩并且修改引用类型!

将在屏幕外面看不到的图片recycle()需要的时候在生成bitmap