我正在尝试调整大图像的大小。对于小图像,此代码可以正常工作,但是对于大图像,outHeight 和 outWidth 始终为 -1,从而创建 NullPointerException。这特别奇怪,因为我设置了 options.inJustDecodeBounds = true,这应该可以防止这种错误,因为内存使用量减少了。我错过了什么吗?我的方法如下:
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e1) {
Log.d("onActivityResult", "FileNotFoundException");
e1.printStackTrace();
}
BitmapFactory.decodeStream(inputStream, null, options);
try {
inputStream.close();
} catch (IOException e1) {
Log.d("onActivityResult", "IOException");
e1.printStackTrace();
}
options.inJustDecodeBounds = false;
options.inSampleSize = calculateInSampleSize(options, IMAGE_SIZE,
IMAGE_SIZE);
InputStream inputStreamTwo = null;
try {
inputStreamTwo = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
Log.d("onActivityResult", "FileNotFoundException");
e.printStackTrace();
}
Bitmap unscaledImage = BitmapFactory.decodeStream(inputStreamTwo,
null, options);
image = Bitmap.createScaledBitmap(unscaledImage, IMAGE_SIZE,
IMAGE_SIZE, false);
Log.d("Unscaled image byte count",
"Bytes: " + unscaledImage.getByteCount());
Log.d("Scaled image byte count", "Bytes: " + image.getByteCount());
}
}
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);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
谢谢您的帮助!
更新:这也发生在 JPG 的小图像(大约 100KB)上。手机相机拍摄的较大 JPG (1.2MB) 不会发生这种情况。