2014-10-09 18 views
0

即時通訊嘗試調整方法來防止從互聯網位圖讀取時出現outOfMemoryError。我是否正確使用它?流是不是從互聯網上讀取兩次?計算採樣圖像時InputStream讀取兩次?

BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inJustDecodeBounds = true; 
URL url = new URL(imageUrl); 
InputStream inputStream = url.openConnection().getInputStream(); 
BitmapFactory.decodeStream(inputStream, null, options); 

// Calculate inSampleSize 
int coverDimensions = CommonTasks.getDisplayMinSize(getActivity()); 
options.inSampleSize = calculateInSampleSize(options, coverDimensions, coverDimensions); 

// Decode bitmap with inSampleSize set 
options.inJustDecodeBounds = false; 
return BitmapFactory.decodeStream(inputStream, null, options); 

private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { 
     // Raw height and width of image 
     final int height = options.outHeight; 
     final int width = options.outWidth; 
     int inSampleSize = 1; 

     if (height > reqHeight || width > reqWidth) { 
      final int halfHeight = height/2; 
      final int halfWidth = width/2; 

      // Calculate the largest inSampleSize value that is a power of 2 and keeps both 
      // height and width larger than the requested height and width. 
      while ((halfHeight/inSampleSize) > reqHeight 
        && (halfWidth/inSampleSize) > reqWidth) { 
       inSampleSize *= 2; 
      } 
     } 

     return inSampleSize; 
    } 
+0

它看起來像這甚至不編譯,請給我們完整的方法/ class-bodys – user2504380 2014-10-09 08:40:54

回答

0

while使用||保持寬度和高度withing邊界。和沒有,你不能重讀一個InputStream。

號理論上你可以使用reset()但互聯網是順序I/O:

boolen canReset = inputStream.markSupported(); 
if (canReset) { 
    inputStream.mark(Integer.MAX_VALUE); 
} 
... first read 
if (canReset) { 
    inputStream.reset(); 
} 
... second read 

而是一個布爾標誌,上電覆位抓住一個IOException,會更容易:它可能是反正當拋出例如超出讀取限制。

只需重讀。第二次它可能來自緩存。