我在嘗試解碼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),除了特定照片。我在這裏錯過了什麼嗎? 謝謝!
最近的電源是的,這是6,因爲req_width和req_height我所以2448/414 = 5.913 - >四捨五入爲6. – joan