2012-05-27 39 views
10

我正在建造一個android的地方。在一項活動中,我有一個圖像按鈕。當我點擊它時,畫廊打開,我可以選擇一個圖像。然後,我將該圖像設置爲圖像按鈕的新圖像。 問題是在我的活動中圖像顯得太大了。我如何使它適合我的圖像按鈕?如何調整我從Android中的圖庫中挑選的圖像?

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch(requestCode) { 
    case SELECT_PHOTO: 
     if(resultCode == RESULT_OK){ 
      Uri selectedImage = imageReturnedIntent.getData(); 
      String[] filePathColumn = {MediaStore.Images.Media.DATA}; 

      Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); 
      cursor.moveToFirst(); 

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
      String filePath = cursor.getString(columnIndex); 
      cursor.close(); 


      Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath); 

      mImageButton.setImageBitmap(yourSelectedImage); 
     } 
    } 
} 

回答

33

你可以使用此方法獲取調整大小的圖像。這樣就可以避免的OutOfMemoryError

public static Bitmap decodeUri(Context c, Uri uri, final int requiredSize) 
      throws FileNotFoundException { 
     BitmapFactory.Options o = new BitmapFactory.Options(); 
     o.inJustDecodeBounds = true; 
     BitmapFactory.decodeStream(c.getContentResolver().openInputStream(uri), null, o); 

     int width_tmp = o.outWidth 
       , height_tmp = o.outHeight; 
     int scale = 1; 

     while(true) { 
      if(width_tmp/2 < requiredSize || height_tmp/2 < requiredSize) 
       break; 
      width_tmp /= 2; 
      height_tmp /= 2; 
      scale *= 2; 
     } 

     BitmapFactory.Options o2 = new BitmapFactory.Options(); 
     o2.inSampleSize = scale; 
     return BitmapFactory.decodeStream(c.getContentResolver().openInputStream(uri), null, o2); 
    } 
+2

你能解釋'requiredSize'參數是什麼意思嗎? – TrungDQ

3

請參閱本LINK

用途:Bitmap.createScaledBitmap(位圖SRC,詮釋dstWidth,INT dstHeight,布爾過濾器)

或使用這些方法::

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) { 
    int width = bm.getWidth(); 
    int height = bm.getHeight(); 
    float scaleWidth = ((float) newWidth)/width; 
    float scaleHeight = ((float) newHeight)/height; 

    // create a matrix for the manipulation 
    Matrix matrix = new Matrix(); 

    // resize the bit map 
    matrix.postScale(scaleWidth, scaleHeight); 

    // recreate the new Bitmap 
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false); 

    return resizedBitmap; 
} 
+0

我會調用該方法後:位圖yourSelectedImage = BitmapFactory.decodeFile(文件路徑); – user1420042

+0

是的,你可以調用 –

+0

,但是我得到一個運行時錯誤 – user1420042

相關問題