2 回答

TA貢獻1725條經驗 獲得超8個贊
bmpFactoryOptions的用法錯了,設置inJustDecodeBounds為true后,decodeFile并不分配空間,但可計算出原始圖片的長度和寬度。有了這兩個參數,再通過一定的算法,即可得到一個恰當的inSampleSize。下面添加了一種動態計算的方法,使用該算法,就可動態計算出圖片的inSampleSize。
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
// 取得返回數據的Uri
Uri imageFileUri = data.getData();
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
try {
BitmapFactory
.decodeStream(
getContentResolver().openInputStream(
imageFileUri), null, bmpFactoryOptions);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
bmpFactoryOptions.inSampleSize = computeSampleSize(
bmpFactoryOptions, -1, 800 * 480);
bmpFactoryOptions.inJustDecodeBounds = false;
Bitmap bmp = null;
try {
bmp = BitmapFactory
.decodeStream(
getContentResolver().openInputStream(
imageFileUri), null, bmpFactoryOptions);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageView imv = (ImageView) findViewById(R.id.imageView1);
imv.setImageBitmap(bmp);
}
}
public static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
Math.floor(w / minSideLength),
Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}

TA貢獻1875條經驗 獲得超5個贊
個人猜測你的代碼應該拋出了空指針異常
bmpFactoryOptions.inJustDecodeBounds = true;
這句話去掉就沒問題了,但是以后可能還會拋OOM異常
bmpFactoryOptions的用法好像你還不會,那就先不要亂用
- 2 回答
- 0 關注
- 184 瀏覽
添加回答
舉報