从android中的文件路径获取内容uri

pan*_*wal 252 android image

我知道图像的绝对路径(比如说/sdcard/cats.jpg).这个文件的内容是否有任何方法?

实际上在我的代码中我下载了一个图像并将其保存在特定位置.为了在ImageView中设置图像,我使用路径打开文件,获取字节并创建位图,然后在ImageView中设置位图.这是一个非常缓慢的过程,相反,如果我可以获得内容uri,那么我可以很容易地使用该方法 ImageView.setImageUri(uri)

Fra*_*ita 461

试试:

ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));
Run Code Online (Sandbox Code Playgroud)

或者:

ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));
Run Code Online (Sandbox Code Playgroud)

  • 不要硬编码"/ sdcard /"; 请改用Environment.getExternalStorageDirectory().getPath() (37认同)
  • 这些方法都不会解析内容URI的文件路径.据我所知,它解决了眼前的问题. (27认同)
  • 这就是上述解决方案返回的内容:1.file:///storage/emulated/0/DCIM/Camera/VID_20140312_171146.mp4 2./storage/emulated/0/DCIM/Camera/VID_20140312_171146.mp4但我在寻找什么因为是不同的东西.我需要content:// format URI.Jinal的答案似乎很完美 (7认同)
  • 嘿`Uri.fromFile`将无法在android 26+上运行,你应该使用文件提供程序 (5认同)
  • 谢谢!第二种方法适用于1.6,2.1和2.2,但第一种方法仅适用于2.2 (3认同)

小智 83

UPDATE

这里假设您的媒体(图像/视频)已添加到内容媒体提供商.如果没有,那么您将无法获得所需的内容URL.相反,会有文件Uri.

我的文件浏览器活动也有同样的问题.您应该知道文件的contenturi仅支持图像,音频和视频等媒体库数据.我正在为您提供从sdcard中选择图像来获取图像内容的代码.试试这个代码,也许它对你有用......

public static Uri getImageContentUri(Context context, File imageFile) {
  String filePath = imageFile.getAbsolutePath();
  Cursor cursor = context.getContentResolver().query(
      MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
      new String[] { MediaStore.Images.Media._ID },
      MediaStore.Images.Media.DATA + "=? ",
      new String[] { filePath }, null);
  if (cursor != null && cursor.moveToFirst()) {
    int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
    cursor.close();
    return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
  } else {
    if (imageFile.exists()) {
      ContentValues values = new ContentValues();
      values.put(MediaStore.Images.Media.DATA, filePath);
      return context.getContentResolver().insert(
          MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    } else {
      return null;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 由于 Android 10 中无法访问 DATA 列,您能否为 Android 10 更新此方法? (2认同)

And*_*ser 16

//此代码适用于2.2上的图像,不确定是否有其他媒体类型

   //Your file path - Example here is "/sdcard/cats.jpg"
   final String filePathThis = imagePaths.get(position).toString();

   MediaScannerConnectionClient mediaScannerClient = new
   MediaScannerConnectionClient() {
    private MediaScannerConnection msc = null;
    {
        msc = new MediaScannerConnection(getApplicationContext(), this);
        msc.connect();
    }

    public void onMediaScannerConnected(){
        msc.scanFile(filePathThis, null);
    }


    public void onScanCompleted(String path, Uri uri) {
        //This is where you get your content uri
            Log.d(TAG, uri.toString());
        msc.disconnect();
    }
   };
Run Code Online (Sandbox Code Playgroud)


Jon*_*n O 15

接受的解决方案可能是您的最佳选择,但要在主题行中实际回答问题:

在我的应用程序中,我必须从URI获取路径并从路径获取URI.前者:

/**
 * Gets the corresponding path to a file from the given content:// URI
 * @param selectedVideoUri The content:// URI to find the file path from
 * @param contentResolver The content resolver to use to perform the query.
 * @return the file path as a string
 */
private String getFilePathFromContentUri(Uri selectedVideoUri,
        ContentResolver contentResolver) {
    String filePath;
    String[] filePathColumn = {MediaColumns.DATA};

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

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    filePath = cursor.getString(columnIndex);
    cursor.close();
    return filePath;
}
Run Code Online (Sandbox Code Playgroud)

后者(我为视频做,但也可以通过将MediaStore.Audio(等)替换为MediaStore.Video来用于音频或文件或其他类型的存储内容):

/**
 * Gets the MediaStore video ID of a given file on external storage
 * @param filePath The path (on external storage) of the file to resolve the ID of
 * @param contentResolver The content resolver to use to perform the query.
 * @return the video ID as a long
 */
private long getVideoIdFromFilePath(String filePath,
        ContentResolver contentResolver) {


    long videoId;
    Log.d(TAG,"Loading file " + filePath);

            // This returns us content://media/external/videos/media (or something like that)
            // I pass in "external" because that's the MediaStore's name for the external
            // storage on my device (the other possibility is "internal")
    Uri videosUri = MediaStore.Video.Media.getContentUri("external");

    Log.d(TAG,"videosUri = " + videosUri.toString());

    String[] projection = {MediaStore.Video.VideoColumns._ID};

    // TODO This will break if we have no matching item in the MediaStore.
    Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(projection[0]);
    videoId = cursor.getLong(columnIndex);

    Log.d(TAG,"Video ID is " + videoId);
    cursor.close();
    return videoId;
}
Run Code Online (Sandbox Code Playgroud)

基本上,DATA中柱MediaStore(它要查询或取分节)存储的文件路径,让你用这些信息来关注一下吧.


Thr*_*ian 7

content://从文件创建 Content Uri 的最简单、最可靠的方法是使用FileProvider。FileProvider 提供的 Uri 也可以用于提供 Uri 与其他应用程序共享文件。要从绝对路径获取文件 Uri,File您可以使用 DocumentFile.fromFile(new File(path, name)),它是在 Api 22 中添加的,并且对于以下版本返回 null。

File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = FileProvider.getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以根据使用情况使用这两种方式

Uri uri = Uri.parse("String file location");

要么

Uri uri = Uri.fromFile(new File("string file location"));

我尝试了两种方式,都是有效的.


小智 6

它迟到了,但将来可能会帮助某人。

要获取文件的内容 URI,您可以使用以下方法:

FileProvider.getUriForFile(Context context, String authority, File file)

它返回内容 URI。

检查这个以了解如何设置 FileProvider