IT技术网www.itjs.cn

当前位置:首页 > 开发设计 > Android > Android图片内存溢出的解决方案

Android图片内存溢出的解决方案

发布时间:2015-07-25 00:00 来源:openopen

1.图片内存溢出

默认情况下,每个android程序的dailvik虚拟机的最大堆空间大小为16M

当加载的图片太多或图片过大时经常出现OOM问题

android 中用bitmap 时很容易内存溢出,报如下错误:Java.lang.OutOfMemoryError

Android图片内存溢出的解决方案

2.解决办法

    public Bitmap matrixBitmapSize(Bitmap bitmap, int screenWidth,  
            int screenHight) {  
        //获取当前bitmap的宽高  
        int w = bitmap.getWidth();  
        int h = bitmap.getHeight();  

        Matrix matrix = new Matrix();  
        float scale = (float) screenWidth / w;  
        float scale2 = (float) screenHight / h;  

        // 取比例小的值 可以把图片完全缩放在屏幕内  
        scale = scale < scale2   scale : scale2;  

        // 都按照宽度scale 保证图片不变形.根据宽度来确定高度  
        matrix.postScale(scale, scale);  
        // w,h是原图的属性.  
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);  
    }  

    public Bitmap optionsBitmapSize(String imagePath, int screenWidth,  
            int screenHight) {  

        // 设置解析图片的配置信息  
        BitmapFactory.Options options = new Options();  
        // 设置为true 不再解析图片 只是获取图片的头部信息及宽高  
        options.inJustDecodeBounds = true;  
        // 返回为null  
        BitmapFactory.decodeFile(imagePath, options);  
        // 获取图片的宽高  
        int imageWidth = options.outWidth;  
        int imageHeight = options.outHeight;  
        // 计算缩放比例  
        int scaleWidth = imageWidth / screenWidth;  
        int scaleHeight = imageHeight / screenHight;  
        // 定义默认缩放比例为1  
        int scale = 1;  
        // 按照缩放比例大的 去缩放  
        if (scaleWidth > scaleHeight & scaleHeight >= 1) {  
            scale = scaleWidth;  
        } else if (scaleHeight > scaleWidth & scaleWidth >= 1) {  
            scale = scaleHeight;  
        }  
        // 设置为true开始解析图片  
        options.inJustDecodeBounds = false;  
        // 设置图片的采样率  
        options.inSampleSize = scale;  
        // 得到按照scale缩放后的图片  
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);  
        return bitmap;  
    }