高效加载图片

如何高效加载Bitmap呢,其实核心思想很简单,就是采用BitmapFactory.Options来加载所需尺寸的图片,假设通过imageview来显示图片,很多时候控件的尺寸并没有图片的原始尺寸那么大,这时候如果加载整个图片是没必要的,所以我们可以通过按一定的采样率来加载缩小后的图片。采样率 inSampleSize,当这个值为1时 采样后图片为图片的原始大小,如果为2 那么久为原图的2/1.像素则为原图的4/1.占的内存也为原图的4/1. inSampleSize 的指数应为2的指数

具体实现如下

package com.example.liwenjie.firstapp.utils;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * Created by liwenjie on 2016/4/7 17:16
 * 高效加载图片
 */
public class BitmapUtils {

    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }


    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 halfHeght = height / 2;
            final int halfWidth = width / 2;

            while ((halfHeght / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }

        }
        return inSampleSize;
    }

}
如果一个imageview需要加载显示则调用 imageview.setImageBitMap(decodeSampledBitmapFromResource(getResources,R.id.myimage,100,100))
)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值