亲测可用,若有疑问请私信

工作中遇到的问题。拍照获取图片后是得到的路径是

 
  1. file:///storage/emulated/0/Android/data/com.zehin.mingchuliangzao3/cache/PostPicture/20160905182015.jpg

但是我想要的路径是:

 
  1. content://media/external/images/media/212304

这种 Uri类型的

查阅资料找到如下方法

转Uri

 
  1. /**

  2. * Gets the content:// URI from the given corresponding path to a file

  3. *

  4. * @param context

  5. * @param imageFile

  6. * @return content Uri

  7. */

  8. public static Uri getImageContentUri(Context context, java.io.File imageFile) {

  9. String filePath = imageFile.getAbsolutePath();

  10. Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,

  11. new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ",

  12. new String[] { filePath }, null);

  13. if (cursor != null && cursor.moveToFirst()) {

  14. int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));

  15. Uri baseUri = Uri.parse("content://media/external/images/media");

  16. return Uri.withAppendedPath(baseUri, "" + id);

  17. } else {

  18. if (imageFile.exists()) {

  19. ContentValues values = new ContentValues();

  20. values.put(MediaStore.Images.Media.DATA, filePath);

  21. return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

  22. } else {

  23. return null;

  24. }

  25. }

  26. }

Uri转绝对路径

 
  1. /**

  2. * Gets the corresponding path to a file from the given content:// URI

  3. * @param selectedVideoUri The content:// URI to find the file path from

  4. * @param contentResolver The content resolver to use to perform the query.

  5. * @return the file path as a string

  6. */

  7. public static String getFilePathFromContentUri(Uri selectedVideoUri,

  8. ContentResolver contentResolver) {

  9. String filePath;

  10. String[] filePathColumn = {MediaColumns.DATA};

  11. Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);

  12. // 也可用下面的方法拿到cursor

  13. // Cursor cursor = this.context.managedQuery(selectedVideoUri, filePathColumn, null, null, null);

  14. cursor.moveToFirst();

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

  16. filePath = cursor.getString(columnIndex);

  17. cursor.close();

  18. return filePath;

  19. }

绝对路径转Uri的那个方法 目前是图片文件的转换 转其他文件 只要把content后面的目录换成对应文件的归属目录就行了。。


 

更多推荐

Android 文件绝对路径和Content开头的Uri互相转换