Android圖片內存溢出處理

jopen 9年前發布 | 12K 次閱讀 Android Android開發 移動開發

1.圖片內存溢出

默認情況下,每個android程序的dailvik虛擬機的最大堆空間大小為16M
當加載的圖片太多或圖片過大時經常出現OOM問題
android 中用bitmap 時很容易內存溢出,報如下錯誤:Java.lang.OutOfMemoryError


2.解決辦法

    public Bitmap matrixBitmapSize(Bitmap bitmap, int screenWidth,
int screenHight) {
//獲取當前bitmap的寬高
int w = bitmap.getWidth();
int h = bitmap.getHeight();

    Matrix matrix = new Matrix();  
    float scale = (float) screenWidth / w;  
    float scale2 = (float) screenHight / h;  

    // 取比例小的值 可以把圖片完全縮放在屏幕內  
    scale = scale < scale2 ? scale : scale2;  

    // 都按照寬度scale 保證圖片不變形.根據寬度來確定高度  
    matrix.postScale(scale, scale);  
    // w,h是原圖的屬性.  
    return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);  
}  

public Bitmap optionsBitmapSize(String imagePath, int screenWidth,  
        int screenHight) {  

    // 設置解析圖片的配置信息  
    BitmapFactory.Options options = new Options();  
    // 設置為true 不再解析圖片 只是獲取圖片的頭部信息及寬高  
    options.inJustDecodeBounds = true;  
    // 返回為null  
    BitmapFactory.decodeFile(imagePath, options);  
    // 獲取圖片的寬高  
    int imageWidth = options.outWidth;  
    int imageHeight = options.outHeight;  
    // 計算縮放比例  
    int scaleWidth = imageWidth / screenWidth;  
    int scaleHeight = imageHeight / screenHight;  
    // 定義默認縮放比例為1  
    int scale = 1;  
    // 按照縮放比例大的 去縮放  
    if (scaleWidth > scaleHeight & scaleHeight >= 1) {  
        scale = scaleWidth;  
    } else if (scaleHeight > scaleWidth & scaleWidth >= 1) {  
        scale = scaleHeight;  
    }  
    // 設置為true開始解析圖片  
    options.inJustDecodeBounds = false;  
    // 設置圖片的采樣率  
    options.inSampleSize = scale;  
    // 得到按照scale縮放后的圖片  
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);  
    return bitmap;  
}  </pre><br />
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!