1

尝试解码 2448x2448 像素大小的照片时,我遇到了奇怪的行为。在代码中,我正在计算应该应用 6 的 inSampleSize(基于生成的位图所需的大小),当我使用这些选项调用 BitmapFactory.decodeStream 时,我期待这样的位图:

  • full_photo_width = 2448
  • 全照片高度 = 2448
  • 样本大小 = 6
  • 预期宽度 = (2448 / 6) = 408
  • 预期高度 (2448 / 6) = 408
  • 实际宽度 = 612
  • 实际高度 = 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)的位图,特定照片除外。我在这里错过了什么吗?谢谢!

4

1 回答 1

2

请参考官方 API 文档:inSampleSize

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

于 2013-10-24T07:36:23.653 回答