AndroidのBitmap之大图片优化

 

不解释大家懂得,在listview 或grid或viewpager等大量大尺寸图片时,会造成OOM

这里是优化图片内存的一个方法,注释写的很 明确..

 

public Bitmap getBitmapFromNet(final String url,final int width,final int height){//从网络下载图片
        try {
            
            //图片内存算法
            //width*height*Config(480*320*ARGB_8888)——>480*320*4 byte
            
            BitmapFactory.Options opt = new BitmapFactory.Options();
            
            /*组合使用*/
            opt.inPurgeable = true;
            opt.inInputShareable = true;
            
            opt.inPreferredConfig = Bitmap.Config.RGB_565;
            
            opt.outWidth = width;
            opt.outHeight = height;
            opt.inJustDecodeBounds = true;//设置为true将不会返回真正图片
            
            int yRatio = (int)Math.ceil(opt.outHeight/height);  
            int xRatio = (int)Math.ceil(opt.outWidth/width);  
               
            if (yRatio > 1 || xRatio > 1){  
             if (yRatio > xRatio) {  
              opt.inSampleSize = yRatio;   //缩放值
             }  
             else {  
              opt.inSampleSize = xRatio;    
             }  
            }  
            //忘了加上这句(重要)
            opt.inJustDecodeBounds = false;//还原图片
            
            Bitmap bitmap = BitmapFactory.decodeStream(new URL(url).openStream(),null,opt);
            //bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
            cache.put(url, new SoftReference<Bitmap>(bitmap));//保存缓存--------->缓存Map
            return bitmap;
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return null;
    }

 

按照我以上的代码是获取不到图片的,

不好意识,忘了加一句,opt.inJustDecodeBounds = false;这句得放在opt.inSampleSize = yRatio; 后面。

只有把缩放值设定好了以后,再把inJustDecodeBounds属性设置为false,因为先把inJustDecodeBounds设为true,此时返回的bitmap为null,但是保存了原始图片的大小。

inSampleSize缩放值设置好了,option就会根据原来的尺寸缩小,然后把再把inJustDecodeBounds设为false的时候,这时就会返回按缩放值缩小后的图片返回到bitmap。

posted @ 2013-01-08 18:18  bvin  阅读(2169)  评论(1编辑  收藏  举报