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

来源:互联网 发布:墙面漆 知乎 编辑:程序博客网 时间:2024/04/29 14:26

开发时使用的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(图片原始大小)
0 0
原创粉丝点击