gpt4 book ai didi

android - NullPointerException 从文件 Android 重新缩放位图

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

一个月以来我一直面临这个问题,没有解决方案:我需要将文件转换为位图并重新缩放。我正在使用以下方法,取自 android 指南:Loading Large Bitmaps Efficiently

public Bitmap decodeSampledBitmapFromFile(String path, int reqSize) {

// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inMutable = true;
BitmapFactory.decodeFile(path, options);

// Calculate inSampleSize
double ratio = (double) options.outHeight / options.outWidth;
boolean portrait = true;
if (ratio < 1) {
portrait = false;
}

double floatSampleSize = options.outHeight / (double)reqSize;
options.inSampleSize = (int) Math.floor(floatSampleSize);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap resultBitmap = BitmapFactory.decodeFile(path, options);

if(floatSampleSize % options.inSampleSize != 0){
if(portrait) {
resultBitmap = Bitmap.createScaledBitmap(resultBitmap, (int)(reqSize/ratio), reqSize, true);
} else {
resultBitmap = Bitmap.createScaledBitmap(resultBitmap, reqSize, (int)(ratio*reqSize), true);
}
}

return resultBitmap;
}

我有相同的 NullPointerException 但我无法重现它:

NullPointerException (@Utilities:decodeSampledBitmapFromFile:397) {AsyncTask #2}
NullPointerException (@Utilities:decodeSampledBitmapFromFile:399) {AsyncTask #3}

第 397 和 399 行是:

resultBitmap = Bitmap.createScaledBitmap(resultBitmap, (int)(reqSize/ratio), reqSize, true);
resultBitmap = Bitmap.createScaledBitmap(resultBitmap, reqSize, (int)(ratio*reqSize), true);

在此设备型号中:

ST21a
U9500
M7
U8950-1

GT-I9305

有人可以帮我解决这个问题吗?是 BitmapFactory.decodeFile 返回 null 吗?非常感谢你

最佳答案

试试这个希望对你有用

public Bitmap decodeFile(String path, int reqSize) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = reqSize;

// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;

// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;

}

关于android - NullPointerException 从文件 Android 重新缩放位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23654074/

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