2016-12-27 23 views
1

以下是由google提供的this link的方法。InSampleSize在Android中計算錯誤嗎?

public static 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; 
} 

如果有其需要被調整大小爲100 * 100 500 * 500圖像,此代碼段的結果是4,因爲它們使用和halfWidthhalfHeight。但是,如果我理解正確的話,結果應該是8.我覺得代碼應該修改爲:

while ((halfHeight/inSampleSize) > reqHeight 
      && (halfWidth/inSampleSize) > reqWidth) { 
     inSampleSize *= 2; 
    } 
inSampleSize *= 2; 

任何人都可以解釋一下嗎?我發現他們已經多次修改了這段代碼,但似乎仍然是錯誤的?

回答

1

這個想法是,圖像按兩個步驟按比例縮小:首先是2的最大功率小於或等於所需的下采樣因子,然後小於2的量以最終結束請求的圖像大小。

如果有500 * 500的圖片需要調整到100 * 100,這段代碼的結果是4,因爲它們使用halfWidth和halfHeight。但是如果我理解正確,結果應該是8.

如果比例因子是8,那麼500x500像素的圖像將縮小到62x62像素,然後需要按比例放大到請求的比例大小爲100x100像素。

正如代碼評論說:

計算最大inSampleSize值是2的冪,保持高度和寬度比所要求的高度和寬度。

這將是4,因爲那麼您將最終得到125x125像素的圖像,該圖像大於請求的100x100像素的高度和寬度。這個想法是,你最終想在最後一步縮小比例,而不是縮小太多,然後縮小比例並獲得模糊的圖像。

所需向下採樣因子爲5,和大於2小於或等於的最高功率爲4

+0

謝謝,解釋是正確的。但我覺得所要求的規模應該是你無法跨越的底線。對於700 * 700的圖像,重新採樣的尺寸爲175 * 175,似乎太大。這是模糊和記憶之間的折衷。 –