Android 加载图片优化(一)

高效加载大图片Bitmap

由于设备限制等原因当一张质量非常高的图片显示在设备终端上我们可能不需要将它完美的展示在应用上 而是展示符合我们设备显示分辨率的图片就好,即显示缩率图。

如果我们完全展示一张或多张高深度大尺寸图片我们会发现系统非常吃力而且还会内存溢出。今天介绍的就是合理展示图片后续还会介绍线程加载图片,内存缓存图片,磁盘缓存图片

1.通过 BitmapFactory.Options  在图片加载到内存之前先读取图片的边界

1 BitmapFactory.Options options = new BitmapFactory.Options();
2 options.inJustDecodeBounds = true;   //只加载边界
3 BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
4 int imageHeight = options.outHeight;
5 int imageWidth = options.outWidth;
6 String imageType = options.outMimeType;

2.计算一个压缩比例

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float)height / (float)reqHeight);
        } else {
            inSampleSize = Math.round((float)width / (float)reqWidth);
        }
    }
    return inSampleSize;
}

3.利用BitmapFacoty.decode(...,BitmapOptions option)方法加载图片

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}
原文地址:https://www.cnblogs.com/qingducx/p/5156288.html