Android Bitmap 內存溢出解決方法

在上一篇中,提到從數據庫中取出圖片數據,構造Bitmap對象時,可能會造成內存溢出,現在提出解決方法

	public static Bitmap bitmpCulate(byte[] data){
		BitmapFactory.Options opts = new BitmapFactory.Options();  
//		opts.inJustDecodeBounds = true;  
//		BitmapFactory.decodeByteArray(data, 0, data.length, opts);
	 
		opts.inSampleSize = computeSampleSize(opts, -1, 128*128);  
		opts.inJustDecodeBounds = false;  
		 
		return  BitmapFactory.decodeByteArray(data, 0, data.length, opts); 
	}
接上一篇:從數據庫中取到字節數組對象,作爲參數,調用此方法返回Bitmap對象。
注意一點:
  參數data類型並不是固定,因爲從數據庫讀取出的圖片數據是以字節數組類型呈現,因此參數爲字節數據類型,如果圖片數據保存在其他數據對象中,只需改變形式參數的類型以及最後 return處,構造Bitmap的方法
在上述方法中用到其他方法代碼如下:
	public static Bitmap bitmpCulate(InputStream is){
		BitmapFactory.Options opts = new BitmapFactory.Options();  
		opts.inJustDecodeBounds = true;  
		BitmapFactory.decodeStream(is, null, opts);
//		BitmapFactory.decodeByteArray(data, 0, data.length, opts);
		opts.inSampleSize = computeSampleSize(opts, -1, 128*128);  
		opts.inJustDecodeBounds = false;  
		 
		return  BitmapFactory.decodeStream(is, null, opts); 
	}

	public static int computeSampleSize(BitmapFactory.Options options,
	        int minSideLength, int maxNumOfPixels) {
	    int initialSize = computeInitialSampleSize(options, minSideLength,maxNumOfPixels);

	    int roundedSize;
	    if (initialSize <= 8 ) {
	        roundedSize = 1;
	        while (roundedSize < initialSize) {
	            roundedSize <<= 1;
	        }
	    } else {
	        roundedSize = (initialSize + 7) / 8 * 8;
	    }

	    return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {
	    double w = options.outWidth;
	    double h = options.outHeight;

	    int lowerBound = (maxNumOfPixels == -1) ? 1 :
	            (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
	    int upperBound = (minSideLength == -1) ? 128 :
	            (int) Math.min(Math.floor(w / minSideLength),
	            Math.floor(h / minSideLength));

	    if (upperBound < lowerBound) {
	        // return the larger one when there is no overlapping zone.
	        return lowerBound;
	    }

	    if ((maxNumOfPixels == -1) &&
	            (minSideLength == -1)) {
	        return 1;
	    } else if (minSideLength == -1) {
	        return lowerBound;
	    } else {
	        return upperBound;
	    }
	}
	




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章