android 加载图片时,内存溢出

以下从网上搜集整理的


从网络读取图片,流的形式

InputStream is = new FlushedInputStream(i);//图片流
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 3; //width,hight设为原来的3分一
d=BitmapFactory.decodeStream(is,null,options);


加载本地大图片

realpath为本地图片路径

bmp = ImageUtil.safeDecodeStream(Uri.fromFile(new File(realPath)),
width, height, getActivity());

/** 
     * A safer decodeStream method 
     * rather than the one of {@link BitmapFactory} 
     * which will be easy to get OutOfMemory Exception 
     * while loading a big image file. 
     *  
     * @param uri 图片路径
     * @param width  需要的宽度
     * @param height  需要的高度
     * @return  二次采样后的bitmap对象
     * @throws FileNotFoundException 
     */  
    public static  Bitmap safeDecodeStream(Uri uri, int width, int height,Context context)  
    throws FileNotFoundException{  
        int scale = 1;  
        BitmapFactory.Options options = new BitmapFactory.Options();  
        android.content.ContentResolver resolver = context.getContentResolver();  
          
        if(width>0 || height>0){  
            // Decode image size without loading all data into memory  
            options.inJustDecodeBounds = true;  
            BitmapFactory.decodeStream(  
                    new BufferedInputStream(resolver.openInputStream(uri), 16*1024),  
                    null,  
                    options);  
              
            int w = options.outWidth;  
            int h = options.outHeight;  
            while (true) {  
                if ((width>0 && w/2 < width)  
                        || (height>0 && h/2 < height)){  
                    break;  
                }  
                w /= 2;  
                h /= 2;  
                scale *= 2;  
            }  
        }  
  
        // Decode with inSampleSize option  
        options.inJustDecodeBounds = false;  
        options.inSampleSize = scale;  
        return BitmapFactory.decodeStream(  
                new BufferedInputStream(resolver.openInputStream(uri), 16*1024),   
                null,   
                options);  
    } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值