很多人在android开发中都遇到了生成bitmap时候内存溢出,也就是out of memory(OOM)的问题,网上对这样的问题的的解决说法不一。笔者作为一个初级开发者,在这里向大家提供一种比较实用,比较易于理解的方法,这种方法不如一些高级开发者提出的方案来的深刻,但是也能帮助大家有效地解决问题。
废话不多说了,直接上代码。

  1. BitmapFactory.Options opt = new BitmapFactory.Options();
  2. //这个isjustdecodebounds很重要
  3. opt.inJustDecodeBounds = true;
  4. bm = BitmapFactory.decodeFile(absolutePath, opt);
  5. //获取到这个图片的原始宽度和高度
  6. int picWidth  = opt.outWidth;
  7. int picHeight = opt.outHeight;
  8. //获取屏的宽度和高度
  9. WindowManager windowManager = getWindowManager();
  10. Display display = windowManager.getDefaultDisplay();
  11. int screenWidth = display.getWidth();
  12. int screenHeight = display.getHeight();
  13. //isSampleSize是表示对图片的缩放程度,比如值为2图片的宽度和高度都变为以前的1/2
  14. opt.inSampleSize = 1;
  15. //根据屏的大小和图片大小计算出缩放比例
  16. if(picWidth > picHeight){
  17. if(picWidth > screenWidth)
  18. opt.inSampleSize = picWidth/screenWidth;
  19. }
  20. else{
  21. if(picHeight > screenHeight)
  22. opt.inSampleSize = picHeight/screenHeight;
  23. }
  24. //这次再真正地生成一个有像素的,经过缩放了的bitmap
  25. opt.inJustDecodeBounds = false;
  26. bm = BitmapFactory.decodeFile(absolutePath, opt);
  27. //用imageview显示出bitmap
  28. iv.setImageBitmap(bm);

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了!

下面这个参数就是跟压缩图片有关的部分,很容易懂,不多解释了:

inSampleSize 的介绍
public int inSampleSize 
Since: API Level 1 
If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value

REFERENCES:http://moto0421.iteye.com/blog/1153657

最新文章

  1. java并发:同步容器&并发容器
  2. 【转】利用mybatis-generator自动生成代码
  3. java_IO读写模版
  4. ES6学习目录
  5. 【Oracle】控制文件管理
  6. MongoDB的安装和使用指南
  7. 【翻译】Sencha Ext JS 5发布
  8. ArrayList如何扩容?
  9. BZOJ 3456: 城市规划 与 多项式求逆算法介绍(多项式求逆, dp)
  10. [转]11个教程中不常被提及的JavaScript小技巧
  11. kubernetes 一个服务的基本组成
  12. bzoj2288 生日礼物 (线段树)
  13. disjoint set
  14. .NetCore实践篇:分布式监控系统zipkin踩坑之路(二)
  15. 技嘉B75-D3V主板BUG
  16. scrapy-下载器中间件
  17. express4.x Request对象获得参数方法小谈【原创】
  18. Java 中 String 的常用方法(二)
  19. LeetCode OJ:Implement Stack using Queues(队列实现栈)
  20. 新标准C++程序设计读书笔记_继承和多态

热门文章

  1. (原)tensorflow中finetune某些层
  2. <转>LUA语法分析
  3. HDUOJ---老人是真饿了
  4. java struts2入门学习---文件下载的二种方式
  5. java struts2入门学习---拦截器学习
  6. 【LeetCode】208. Implement Trie (Prefix Tree)
  7. IPsec ISAKMP(转)
  8. 【Oracle】Oracle约束的总结
  9. span的赋值与取值
  10. easyui datagrid checkbox选中事件