Android优化图片加载所占用的内存

开发时使用的imagview所需要显示的图片大小比图片的真实大小小时,如果完全加载图片真实的大小会造成内存的浪费,Android官方提供了优化的方案,现整理出核心代码如下:

    /**
     * 只读取图片的长宽边界,不是真正的加载图片
     * @param resourceId
     * @return
     */
    private BitmapFactory.Options getOptions(int resourceId){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//设为true,不是真正的读取图片
        BitmapFactory.decodeResource(getResources(),resourceId,options);
        int h = options.outHeight;
        int w = options.outWidth;
        Bitmap bitmap = options.inBitmap;//bitmap为null
        Log.d(TAG,"h:"+h+",w:"+w+",bitmap:"+String.valueOf(bitmap==null));
        return  options;
    }

    /**
     * 获取图片的缩放比例,根据所需的长宽与实际长宽的比例来计算
     * inSampleSize>=1,并且是2的指数,inSampleSize为4,最后实际加载的图片长宽分别为
     * 真实长宽的1/4,大小是原来的1/16
     * @param options
     * @param reqHeight
     * @param reqWidth
     * @return
     */
    private int getInsampleSize(BitmapFactory.Options options,int reqHeight,int reqWidth) {
        int height = options.outHeight;
        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;
    }

    /**
     * 获取最终加载的bitmap
     * @param resourceId
     * @param reqHeight
     * @param reqWidth
     * @return
     */
    private Bitmap getBitmap(int resourceId,int reqHeight,int reqWidth){
        BitmapFactory.Options options = getOptions(resourceId);
        int inSampleSize = getInsampleSize(options,reqHeight,reqWidth);
        options.inSampleSize = inSampleSize;
        options.inJustDecodeBounds = false;//设置为false真实的加载图片
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),resourceId,options);
        return bitmap;
    }

方法调用:

        Bitmap bitmap = getBitmap(R.mipmap.ic_launcher,32,32);
        Bitmap b2 = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
        Log.d(TAG,bitmap.getWidth()+":"+bitmap.getHeight());
        Log.d(TAG,b2.getWidth()+":"+b2.getHeight());

最后得到的结果是:

07-19 09:46:28.469 7169-7169/com.example.archermind.myapplication D/BitmapOptions: 36:36(通过优化方案得到的图片大小)
07-19 09:46:28.469 7169-7169/com.example.archermind.myapplication D/BitmapOptions: 144:144(图片原始大小)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值