2014-11-17 235 views
8

我有圖像文件的Uri。從URI獲取文件路徑

我用這個代碼會從開放的文件路徑:

public String getRealPathFromURI(Uri contentUri) { 
    Cursor cursor = null; 
    try { 
     String[] proj = { MediaStore.Images.Media.DATA }; 
     cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null); 
     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
     cursor.moveToFirst(); 
     return cursor.getString(column_index); 
    } catch (Exception e) { 
     Log.message(e.getMessage()); 
    } finally { 
     if (cursor != null) { 
      cursor.close(); 
     } 
    } 
    return null; 
} 

如果我從圖庫應用程序選擇圖像(是Android 4.4.2,手臂動車組),

uri.getPath = /external/images/media/16 and it work's fine (My file path: /storage/sdcard/Download/0_cf15a_7800a7e5_orig.jpg) 

如果讓我選擇從文檔中應用圖片(是Android 4.4.2,手臂動車組),

I have uri.getPath = /document/image:16 and function getRealPathFromURI returns null. 

我怎樣才能返回立案boths行動正確的路徑?

我的代碼是: -

@Override 
    public void onClick(View v) { 
     final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "Photohunt" + File.separator); 
     root.mkdirs(); 
     final String fname = Common.getUniqueImageFilename(); 
     final File sdImageMainDirectory = new File(root, fname); 
     outputFileUri = Uri.fromFile(sdImageMainDirectory); 
      // Camera. 
      final List<Intent> cameraIntents = new ArrayList<Intent>(); 
      final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
      final PackageManager packageManager = mContext.getPackageManager(); 
      final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0); 
      for(ResolveInfo res : listCam) { 
       final String packageName = res.activityInfo.packageName; 
       final Intent intent = new Intent(captureIntent); 
       intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); 
       intent.setPackage(packageName); 
      intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); 
       cameraIntents.add(intent); 
      } 

      // Filesystem. 
      final Intent galleryIntent = new Intent(); 
      galleryIntent.setType("image/*"); 
      galleryIntent.setAction(Intent.ACTION_GET_CONTENT); 

      // Chooser of filesystem options. 
      final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source"); 

      // Add the camera options. 
      chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{})); 

      startActivityForResult(chooserIntent, PICTURE_REQUEST_CODE); 
    } 

手柄活動結果:

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    if(resultCode == Activity.RESULT_OK) 
    { 
     if(requestCode == PICTURE_REQUEST_CODE) 
     { 
      final boolean isCamera; 
      if(data == null) 
      { 
       isCamera = true; 
      } 
      else 
      { 
       final String action = data.getAction(); 
       if(action == null) 
       { 
        isCamera = false; 
       } 
       else 
       { 
        isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
       } 
      } 

      Uri selectedImageUri; 
      if(isCamera) 
      { 
       selectedImageUri = outputFileUri; 
      } 
      else 
      { 
       selectedImageUri = data == null ? null : data.getData(); 
      } 

      Log.variable("uri", selectedImageUri.getPath()); 
      ConfirmImageFragment fragment = new ConfirmImageFragment(selectedImageUri, mContestId); 
      FragmentTransaction transaction = getSherlockActivity().getSupportFragmentManager().beginTransaction(); 
      transaction.replace(R.id.main_container, fragment); 
      transaction.addToBackStack(null); 
      transaction.commit(); 
     } 
    } 

    super.onActivityResult(requestCode, resultCode, data); 
} 

加載所選文件到ImageView的工作正常兩種狀態:

private void loadImage() { 
    try { 
     Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), mUri); 
     mImage.setImageBitmap(bitmap); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

回答

18

解決方案:

public class RealPathUtil { 

    @SuppressLint("NewApi") 
    public static String getRealPathFromURI_API19(Context context, Uri uri){ 
     String filePath = ""; 
     String wholeID = DocumentsContract.getDocumentId(uri); 

     // Split at colon, use second item in the array 
     String id = wholeID.split(":")[1]; 

     String[] column = { MediaStore.Images.Media.DATA };  

     // where id is equal to    
     String sel = MediaStore.Images.Media._ID + "=?"; 

     Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
            column, sel, new String[]{ id }, null); 

     int columnIndex = cursor.getColumnIndex(column[0]); 

     if (cursor.moveToFirst()) { 
      filePath = cursor.getString(columnIndex); 
     } 
     cursor.close(); 
     return filePath; 
    } 


    @SuppressLint("NewApi") 
    public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) { 
      String[] proj = { MediaStore.Images.Media.DATA }; 
      String result = null; 

      CursorLoader cursorLoader = new CursorLoader(
        context, 
      contentUri, proj, null, null, null);   
      Cursor cursor = cursorLoader.loadInBackground(); 

      if(cursor != null){ 
      int column_index = 
      cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
      cursor.moveToFirst(); 
      result = cursor.getString(column_index); 
      } 
      return result; 
    } 

    public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){ 
       String[] proj = { MediaStore.Images.Media.DATA }; 
       Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null); 
       int column_index 
      = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
       cursor.moveToFirst(); 
       return cursor.getString(column_index); 
    } 
} 

http://hmkcode.com/android-display-selected-image-and-its-real-path/

+0

謝謝!你救了我的一天;)。 – leegor

+0

DocumentsContract.getDocumentId(uri);它沒有解決,如何組織導入DocumentsContract – Madhu

+0

@Madhu見代碼 – Artem

0

我覺得這應該管用。從路徑獲得URI的通用代碼:

String path = yourAndroidURI.uri.getPath() 
File file = new File(new URI(path)); 
+2

例外:URI不是絕對的:/ document/image:16 – Artem

2

接受答案的簡化版本,將檢測API級別,並使用正確的方法:

@TargetApi(Build.VERSION_CODES.KITKAT) 
public static String getFilePath(Context context, Uri uri) 
{ 
    int currentApiVersion; 
    try 
    { 
     currentApiVersion = android.os.Build.VERSION.SDK_INT; 
    } 
    catch(NumberFormatException e) 
    { 
     //API 3 will crash if SDK_INT is called 
     currentApiVersion = 3; 
    } 
    if (currentApiVersion >= Build.VERSION_CODES.KITKAT) 
    { 
     String filePath = ""; 
     String wholeID = DocumentsContract.getDocumentId(uri); 

     // Split at colon, use second item in the array 
     String id = wholeID.split(":")[1]; 

     String[] column = {MediaStore.Images.Media.DATA}; 

     // where id is equal to 
     String sel = MediaStore.Images.Media._ID + "=?"; 

     Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
       column, sel, new String[]{id}, null); 

     int columnIndex = cursor.getColumnIndex(column[0]); 

     if (cursor.moveToFirst()) 
     { 
      filePath = cursor.getString(columnIndex); 
     } 
     cursor.close(); 
     return filePath; 
    } 
    else if (currentApiVersion <= Build.VERSION_CODES.HONEYCOMB_MR2 && currentApiVersion >= Build.VERSION_CODES.HONEYCOMB) 

    { 
     String[] proj = {MediaStore.Images.Media.DATA}; 
     String result = null; 

     CursorLoader cursorLoader = new CursorLoader(
       context, 
       uri, proj, null, null, null); 
     Cursor cursor = cursorLoader.loadInBackground(); 

     if (cursor != null) 
     { 
      int column_index = 
        cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
      cursor.moveToFirst(); 
      result = cursor.getString(column_index); 
     } 
     return result; 
    } 
    else 
    { 

     String[] proj = {MediaStore.Images.Media.DATA}; 
     Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null); 
     int column_index 
       = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
     cursor.moveToFirst(); 
     return cursor.getString(column_index); 
    } 
} 
+2

你如何實現這個非圖像文件? –

0

所以我基本上都試過在棧上回答,但這是第只有一個爲我工作。將uri視爲圖像所指向的「承諾」是很重要的。這並不意味着在那個位置有一個文件,但如果你問得對,你會得到一個圖像。 attachchementPath是圖像的路徑(可以像普通文件一樣使用)。如下所示:

try { 
      InputStream input = getActivity().getContentResolver().openInputStream(imageUri); 
      File file = new File(getActivity().getCacheDir(), "cacheFileAppeal.png"); 
      try { 

       OutputStream output = new FileOutputStream(file); 
       try { 
        try { 
         byte[] buffer = new byte[4 * 1024]; // or other buffer size 
         int read; 

         if (input != null) { 
          while ((read = input.read(buffer)) != -1) { 
           output.write(buffer, 0, read); 
          } 
         } 
         output.flush(); 
        } finally { 
         output.close(); 
         attachmentPath = file.getAbsolutePath(); 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); // handle exception, define IOException and others 
       } 

      } finally { 
       try { 
        if (input != null) { 
         input.close(); 
        } 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
1

請確保您在Manifest中給予許可。 浪費2小時嘗試各種方法沒有給予權限:/

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
0

公共靜態INT getIdFromUri(URI的URI,字符串constantId) { 光標C = ContentMaster.getContentResolver()的查詢(URI,新的String [] {constantId},null,null,null);

int res = -1; 
    if(c != null && c.getCount() > 0) 
    { 
     c.moveToFirst(); 
     res = c.getInt(0); 
     c.close(); 
    } 
    return res; 
} 
public static Uri getUriWithId(Uri baseUri,int contactId) 
{ 
    Uri u = ContentUris.withAppendedId(baseUri, contactId); 

    if(u != null) 
     return u; 

    return Uri.EMPTY; 
} 
public static String getRealPathFromURI(Uri uri) 
{ 
    if(uri == null) 
     return ""; 

    if ("file".equalsIgnoreCase(uri.getScheme())) 
     return uri.getPath(); 


    String[] pro = { MediaStore.Images.Media.DATA }; 
    String result = null; 
    Cursor cursor; 

    if(VERSION.SDK_INT > 18) 
    { 
     //String wholeID = DocumentsContract.getDocumentId(uri); 
     //String id = wholeID.split(":")[1]; 
     String id = String.valueOf(getIdFromUri(uri, Images.Media._ID)); 
     String[] column = { MediaStore.Images.Media.DATA }; 
     String where = MediaStore.Images.Media._ID + "=?"; 
     Uri u = uri; 

     if(isMediaDocument(uri)) 
     { 
      if (getUriMediaDocumentType(uri).equals("image")) 
      { 
       if(isExternalStorageDocument(uri)) 
        u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 
       else 
        u = MediaStore.Images.Media.INTERNAL_CONTENT_URI; 
      } 
      else if (getUriMediaDocumentType(uri).equals("video")) 
      { 
       if(isExternalStorageDocument(uri)) 
        u = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; 
       else 
        u = MediaStore.Video.Media.INTERNAL_CONTENT_URI; 
      } 
      else if (getUriMediaDocumentType(uri).equals("audio")) 
      { 
       if(isExternalStorageDocument(uri)) 
        u = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 
       else 
        u = MediaStore.Audio.Media.INTERNAL_CONTENT_URI; 
      } 
     } 
     else if(isDownloadsDocument(uri)) 
     { 
      u = getUriWithId(Uri.parse("content://downloads/public_downloads"), Integer.getInteger(id)); 
     } 

     cursor = getContentResolver().query(u, column, where, new String[]{id}, null); 
    } 
    else if(VERSION.SDK_INT > 10) 
    { 
     CursorLoader cursorLoader = new CursorLoader(SystemMaster.getContext(), uri, pro, null, null, null); 
     cursor = cursorLoader.loadInBackground(); 
    } 
    else 
    { 
     cursor = SystemMaster.getContext().getContentResolver().query(uri, pro, null, null, null); 
    } 


    if(cursor != null && cursor.getCount() > 0) 
    { 
     cursor.moveToFirst(); 
     result = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); 
     cursor.close(); 
    } 

    return result; 
} 

public static boolean isExternalStorageDocument(Uri uri) 
{ 
    return "com.android.externalstorage.documents".equals(uri.getAuthority()); 
} 

public static boolean isDownloadsDocument(Uri uri) 
{ 
    return "com.android.providers.downloads.documents".equals(uri.getAuthority()); 
} 

public static boolean isMediaDocument(Uri uri) 
{ 
    return "com.android.providers.media.documents".equals(uri.getAuthority()); 
} 

public static String getUriMediaDocumentType(Uri uri) 
{ 
    if(isMediaDocument(uri)) 
    { 
     //TODO 
     return "image"; 
    } 

    return ""; 
}