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

编程知识 更新时间:2023-04-05 05:24:52

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

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

 
  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互相转换

本文发布于:2023-04-05 05:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/90fec79ce1dc45afbb48496c84022b57.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:开头   绝对路径   文件   Android   Content

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 44996文章数
  • 14阅读数
  • 0评论数