您的位置:首页 > 移动开发 > Android开发

android 加载图片时,内存溢出

2015-01-15 18:24 267 查看
以下从网上搜集整理的

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

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);  

    } 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: