所以,在我的手裏有一個形象Uri
我想找回它的InputStream
,並在內存分配,以避免之前縮小圖像OutOfMemoryException
解決方案:
要從烏里檢索的InputStream,你必須把這個:
InputStream stream = getContentResolver().openInputStream(uri);
然後在loading bitmaps efficiently以下的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;
}
你好,謝謝你的評論。嘗試在縮放之前將Uri傳遞給ImageView也會導致OutOfMemoryException,它的圖像太大。但是你爲我開闢了一個新的選擇,並且基於Uri現在我能夠檢索InputStream並縮小圖像。我會很快發佈解決方案。 – 2012-07-27 11:36:28