2013-02-20 117 views
0

我試圖獲取圖像文件的完整路徑作爲字符串,但它不起作用。我只是得到了像「內容:/外部/媒體/圖像/ 1」的結果。這絕對不是正確的道路。我怎樣才能得到正確的路徑,包括文件擴展名?文件路徑到字符串

這裏是我試過至今:

 public void onClick(View arg0) { 
       switch (arg0.getId()) { 
       case R.id.btnGetImage: 
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
        intent.setType("image/*"); 
        startActivityForResult(Intent.createChooser(intent, "Select A Picture"), 
           PHOTO_GALLERY); 
        break; 
     } 
} 

@Override 
     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     switch(requestCode){ 
     case PHOTO_GALLERY: 
      if (resultCode == RESULT_OK) { 
       File file = new File(data.getDataString()); 
       String imagePath = file.getAbsolutePath(); 
       break; 
      } 
     } 
} 

回答

1

試試這個代碼:

case R.id.btnGetImage: 

     Intent i = new Intent(
       Intent.ACTION_PICK, 
       android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
     startActivityForResult(i, RESULT_LOAD_IMAGE); 
     break; 

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

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK 
      && null != data) { 
     Uri selectedImage = data.getData(); 
     String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

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

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

     ImageView imageView = (ImageView) findViewById(R.id.imageView1); 
     imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); 

    } 

picturePath是你需要的路徑...

+0

這工作絕對好。謝謝! – 2013-02-20 10:38:09

+0

歡迎親愛的:) – Shiv 2013-02-20 10:41:55

0
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    switch(requestCode){ 
    case PHOTO_GALLERY: 
     if (resultCode == RESULT_OK) { 
      Uri selectedImageUri = data.getData(); 
     String selectedImagePath = getRealPathFromURI(selectedImageUri); 
      File file = new File(selectedImagePath); 

      break; 
     } 
    } 
} 
+0

hav你試過這段代碼,它會工作,如果意圖是從畫廊來,如果從文件管理器,你會得到絕對路徑本身 – 2013-02-20 10:33:58

0

你必須定義正確filename到必須在你的SD卡可以存在,而從SD卡獲取您的路徑,

字符串的文件路徑= Environment.getExternalStorageDirectory( )+ 「/文件夾名/」 + test.png;

我聞到你想要做些什麼,比如this