gpt4 book ai didi

android - BitmapFactory.decodeStream 返回错误大小的位图

转载 作者:行者123 更新时间:2023-11-29 21:30:53 26 4
gpt4 key购买 nike

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

  • full_photo_width = 2448
  • full_photo_height = 2448
  • inSampleSize = 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)的位图,特定照片除外。我在这里错过了什么吗?谢谢!

最佳答案

请引用官方API文档:inSampleSize .

Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.

关于android - BitmapFactory.decodeStream 返回错误大小的位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19559655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com