尝试解码大小为2448x2448像素的照片时,我有一种奇怪的行为。在代码中,我正在计算应该应用6的inSampleSize(基于生成的位图的所需大小),当我用这些选项调用BitmapFactory.decodeStream时,我期待这样的位图:
以下是代码:
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),特殊照片除外。我在这里错过了什么吗? 谢谢!