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。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值