因此,Uri
在我手中有一张图像,我想检索它InputStream
并缩小图像,然后再将其分配到内存中以避免OutOfMemoryException
解决方案:
要从 Uri 中检索 InputStream,您必须调用:
InputStream stream = getContentResolver().openInputStream(uri);
然后按照 Android 关于高效加载位图的建议,您只需要调用BitmapFactory.decodeStream()
,并将其BitmapFactory.Options
作为参数传递。
完整源代码:
imageView = (ImageView) findViewById(R.id.imageView);
Uri uri = Uri.parse("android.resource://com.testcontentproviders/drawable/"+R.drawable.test_image_large);
Bitmap bitmap=null;
try {
InputStream stream = getContentResolver().openInputStream(uri);
bitmap=decodeSampledBitmapFromStream(stream, 150, 100);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
imageView.setImageBitmap(bitmap);
辅助方法:
public static Bitmap decodeSampledBitmapFromStream(InputStream stream,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(stream, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(stream, null, options);
}
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) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}