您的位置:首页 > 其它

缩放图片,解决bitmap 内存溢出out of memory的问题

2015-07-27 15:02 836 查看


BitmapFactory.Options opt = new BitmapFactory.Options();
        //这个isjustdecodebounds很重要
        opt.inJustDecodeBounds = true;
        bitmap = BitmapFactory.decodeFile(absolutePathStr, opt);
        //获取到这个图片的原始宽度和高度
        int picWidth  = opt.outWidth;
        int picHeight = opt.outHeight;
        //获取屏的宽度和高度
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int screenWidth = display.getWidth();
        int screenHeight = display.getHeight();
        //isSampleSize是表示对图片的缩放程度,比如值为2图片的宽度和高度都变为以前的1/2
        opt.inSampleSize = 1;
        //根据屏的大小和图片大小计算出缩放比例
        if(picWidth > picHeight){
            if(picWidth > screenWidth)
                opt.inSampleSize = picWidth/screenWidth;
            }
        else{
            if(picHeight > screenHeight)
            opt.inSampleSize = picHeight/screenHeight;
            }
        //这次再真正地生成一个有像素的,经过缩放了的bitmap
        opt.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(absolutePathStr, opt);

inJustDecodeBounds 的介绍

public boolean inJustDecodeBounds 

Since: API Level 1 

If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels. 

就是说,如果设置inJustDecodeBounds为true,仍可以获取到bitmap信息,但完全不用分配内存,因为没有获取像素,所以我们可以利用得到的Bitmap的大小,重新压缩图片,然后在内存中生成一个更小的Bitmap,这样即便是一个4MB的JPG,我们也可以随心所欲地把他压缩到任意大小,从而节省了内存,看到这里是不是恍然大悟,牛b了牛b了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: