尝试解码2448x2448像素大小的照片时,我有一个奇怪的行为。在代码中,我正在计算应应用inSampleSize为6(基于结果位图的所需大小),当我使用这些选项调用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)的位图,但特定照片除外。我在这里想念什么吗?
谢谢!

最佳答案

请参考官方API文档:inSampleSize


  注意:解码器使用基于2的幂的最终值,任何其他值将四舍五入到最接近的2的幂。

10-08 17:51