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

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

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

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


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
blog

 

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

相关文章
相关标签/搜索