2015-05-14 25 views
1

我的應用程序拋出內存異常,同時在我的imageView中將21百萬像素的圖像作爲位圖加載。如何從大位圖採樣圖像時使用URI而不是resID?

Uri imageUri = /* URI goes here */ 
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri); 
Imageview iv = (Imageview) findViewById (R.id.my_img_view); 
iv.setImageBitmap(bitmap); 

所以我在官方的android文檔Loading Large Bitmaps Efficiently中發現了這個頁面。對圖像進行下采樣並在內存中加載較小的版本,而不是加載整個圖像。

問題是此代碼使用ResID而不是URI。

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, 
    int reqWidth, int reqHeight) { 

// First decode with inJustDecodeBounds=true to check dimensions 
final BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inJustDecodeBounds = true; 
BitmapFactory.decodeResource(res, resId, options); 

// Calculate inSampleSize 
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

// Decode bitmap with inSampleSize set 
options.inJustDecodeBounds = false; 
return BitmapFactory.decodeResource(res, resId, options); 
} 

如何將此代碼與已有的URI一起使用?

回答

1

使用BitmapFactory.decodeStream(...)代替BitmapFactory.decodeResource(...)

InputStream inputStream = context.getContentResolver().openInputStream(uri); 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeStream(inputStream, null, options);