缩放图片,解决bitmap 内存溢出out of memory的问题
2015-07-27 15:02
836 查看
//这个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了!
相关文章推荐
- 正则表达式
- CXF实战之在Tomcat中发布Web Service(二)
- 图像去噪 使用dct变换进行去噪
- Android 、切换主题的实现
- temp
- Java基础查漏补缺:(String篇)一个面试题问倒了我,原来String并不简单
- 【转】关于FLASH中图文混排聊天框的小结
- 理解MySQL——索引与优化
- C++遍历目录,并把目录里超过7天的文件删除(跨平台windows&linux)
- 对C++中虚函数的应用所带来的隐藏和重写的探讨
- c语言读写文件
- Android旋转动画
- Android的权限机制之—— “沙箱”机制sharedUserId跟签名
- android setClickable 不起作用 没有作用
- JS相关知识记录
- Win7系统下修改VC6.0的字体
- Android旋转动画
- IOS第四天(3:数组的排序和乱序)
- Web之旅第三站——ASP.NET
- CSS制作响应式正方形及其应用