zoukankan      html  css  js  c++  java
  • 缩放图片,解决bitmap 内存溢出out of memory的问题

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

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

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


    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

  • 相关阅读:
    opencv安装
    安装电脑
    勿忘心安
    Linux操作
    listBox1_DrawItem
    今天被骂
    我研究群体行为,希望大家一起讨论
    Matlab高级绘图
    网址
    下面哪些机制可以用于进程间通信?
  • 原文地址:https://www.cnblogs.com/anee/p/3270270.html
Copyright © 2011-2022 走看看