2016-12-13 121 views
0

我對此很困惑。檢查我的代碼Android在片段中選擇圖片

// Read bitmap 
public Bitmap readBitmap(Uri selectedImage) { 
    Bitmap bm = null; 
    BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inSampleSize = 4; 
    AssetFileDescriptor fileDescriptor = null; 
    try { 
     fileDescriptor = appContext.getContentResolver().openAssetFileDescriptor(selectedImage,"r"); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
    finally{ 
     try { 
      bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options); 
      fileDescriptor.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return bm; 
} 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { 
     Uri filePath = data.getData(); 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inPreferredConfig = Bitmap.Config.ARGB_8888; 
     bitmap = readBitmap(filePath); 
     SuggestImage.setImageBitmap(bitmap); 
    } 
} 

我得到一個錯誤,在這裏

bitmap = readBitmap(filePath); 

稱不兼容的類型要求INT但是當我把和int它說不能適用。需要幫助謝謝

我覺得是因爲它在一個片段中。我認爲問題是我不能得到的ContentResolver,但我不知道

+0

https://github.com/coomar2841/android-multipicker-library –

+1

什麼是位圖變量? –

+0

其位圖位圖; –

回答

0

比方說,你有一個按鈕editPic在你的片段點擊你必須從庫中選擇圖像。使用下面的代碼從庫

editPic.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
        Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
        // ******** code for crop image 
        i.putExtra("crop", "true"); 
        i.putExtra("aspectX", 100); 
        i.putExtra("aspectY", 100); 
        i.putExtra("outputX", 300); 
        i.putExtra("outputY", 300); 
        try { 
         i.putExtra("return-data", true); 
         startActivityForResult(
           Intent.createChooser(i, "Select Picture"), 0); 
        }catch (ActivityNotFoundException ex){ 
         ex.printStackTrace(); 
        } 

      } 
     }); 

實施拾取並在片段

@Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if(requestCode==0 && resultCode == Activity.RESULT_OK){ 
      try { 
       Bundle bundle = data.getExtras(); 
       Bitmap bitmap = bundle.getParcelable("data"); // use this bitmap 
       img.setImageBitmap(bitmap); //set image to imageView 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

希望它會爲你工作,使用下面的onActivityResult的代碼。