2013-10-24 65 views
1

我在嘗試解碼2448x2448像素大小的照片時出現奇怪的行爲。在代碼中,我:計算爲6的inSampleSize應當應用(基於所得位圖的所需尺寸),當我打電話BitmapFactory.decodeStream與這些選項我期待像這樣的位圖:BitmapFactory.decodeStream正在返回錯誤的大小位圖

  • full_photo_width = 2448
  • full_photo_height = 2448
  • inSampleSize = 6
  • expected_width =(2448/6)= 408
  • expected_height(2448/6)= 408
  • actual_width = 612
  • actual_height = 612

下面是代碼:

BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     try { 
      BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options); 
     } catch (FileNotFoundException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     int photo_width = options.outWidth; 
     int photo_height = options.outHeight; 
     float rotation = rotationForImage(this, uri); 
     if (rotation != 0f) { 
      // Assume the photo is portrait oriented 
      matrix.preRotate(rotation); 
      float photo_ratio = (float) ((float)photo_width/(float)photo_height); 
      frame_height = (int) (frame_width/photo_ratio); 

     } else { 
      // Assume the photo is landscape oriented 
      float photo_ratio = (float) ((float)photo_height/(float)photo_width); 
      frame_height = (int) (frame_width * photo_ratio); 

     } 
     int sampleSize = calculateInSampleSize(options, frame_width, frame_height); 
     if ((sampleSize % 2) != 0) { 
      sampleSize++; 
     } 
     options.inSampleSize = sampleSize; 
     options.inJustDecodeBounds = false; 

     Bitmap bitmap = null; 
     try { 
      bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

而且calculateInSampleSize功能:

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) { 

     // Calculate ratios of height and width to requested height and width 
     final int heightRatio = Math.round((float) height/(float) reqHeight); 
     final int widthRatio = Math.round((float) width/(float) reqWidth); 

     inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; 

     // We round the value to the highest, always. 
     if ((height/inSampleSize) > reqHeight || (width/inSampleSize > reqWidth)) { 
      inSampleSize++; 
     } 

    } 

    return inSampleSize; 
} 

代碼工作的所有照片的所有照片和decodeStream是在所有情況下都會返回一個正確大小的位圖(取決於計算的inSampleSize),除了特定照片。我在這裏錯過了什麼嗎? 謝謝!

+0

最近的電源是的,這是6,因爲req_width和req_height我所以2448/414 = 5.913 - >四捨五入爲6. – joan

回答

2

請參考官方API文檔:inSampleSize

注:解碼器使用基於2的冪的最終值,任何其他值將四捨五入到2

+0

哦,所以解碼器在這種情況下應用4,因爲6向下舍入到最接近2的冪? – joan

+0

是的。這正是發生的情況。 –

+0

好吧,我現在看到,我誤解了文檔的那一部分。非常感謝! – joan

相關問題