2010-06-09 160 views
185

我知道图像的绝对路径(比如,/sdcard/cats.jpg)。有没有什么办法可以为这个文件提供内容uri?从android中的文件路径获取内容uri

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

+19

Uri uri = Uri.parse(“file:///sdcard/img.png”); – 2011-09-29 06:39:16

+9

+1的评论,只是Uri.parse(“file://”+ filePath)应该做的窍门 – 2014-03-20 12:03:01

+0

Uri.Parse是折旧和“将被添加” – pollaris 2017-11-29 16:54:04

回答

370

尝试用:

ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg"))); 

或用:

ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString())); 
+3

谢谢!第二种方法在1.6,2.1和2.2上正常工作,但仅在2.2中第一种方法 – mishkin 2010-11-30 02:45:14

+19

这两种方法都不能解析到内容URI的文件路径。我明白它解决了眼前的问题。 – 2011-04-26 20:46:52

+0

如果有SD卡路径,但要内容uri @JO O主意完美工作:http://stackoverflow.com/a/11603841/336990 – CoDe 2012-09-09 08:29:09

13

//此代码适用于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(); 
    } 
    }; 
+1

很好,帮助我分享到Google+,因为该应用需要带有内容的媒体流Uri - 绝对路径不起作用。 – Ridcully 2012-06-18 20:02:18

+0

非常好!我可以确认这也适用于音频媒体类型。 – 2012-08-28 20:00:57

12

接受的s解决方案可能是您的目的最好的选择,但要真正回答主题行中的问题:

在我的应用程序中,我必须从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; 
} 

后者(这是我对影片做的,但也可以通过对MediaStore.Video代MediaStore.Audio(ETC),用于音频或文件或其他类型的存储内容):

/** 
* 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; 
} 

基本上,MediaStoreDATA列(或任何它要查询的子部分)存储的文件路径,让你用这些信息来关注一下吧。

69

UPDATE

这里假设你的媒体(图片/视频)已经加入到内容媒体提供商。如果没有,那么您将无法获得您想要的 内容网址。相反会有文件Uri。

我对我的文件浏览器活动有同样的问题。您应该知道文件的contenturi仅支持图像,音频和视频等媒体存储数据。我给你的代码获取图像内容uri从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; 
    } 
    } 
} 
+0

我正在寻找一种方法来查找我录制的视频文件的内容:// URI,上面的代码似乎在Nexus 4(Android 4.3)上工作得很完美。如果您可以请解释代码,这将是很好的。 – 2014-03-12 12:35:56

+0

我已经尝试过用绝对路径“/ sdcard/Image Depo/picture.png”获取文件的内容Uri。它没有工作,所以我放弃了代码路径,发现Cursor是空的,并且当条目被添加到ContentProvider时,它将给出null作为内容Uri。请帮忙。 – 2015-04-02 08:56:45

+0

这应该是公认的答案!此外,这是当Android试图使用文件:ACTION_IMAGE_CAPTURE拍摄照片时出现Android预览版N(即将推出的API级别24)时应用程序崩溃的修复程序:EXTRA_OUTPUT的Uri值导致FileUriExposedException。只需用'putExtra(MediaStore.EXTRA_OUTPUT,getImageContentUri(con​​text,imageFile))'替换'putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(imageFile))'。 – 2016-04-08 13:53:58

0

获取文件ID,而无需编写任何代码,只需与亚行壳CLI命令:

adb shell content query --uri "content://media/external/video/media" | grep FILE_NAME | grep -Eo " _id=([0-9]+)," | grep -Eo "[0-9]+" 
0

U可以试试下面的代码片段

public Uri getUri(ContentResolver cr, String path){ 
    Uri mediaUri = MediaStore.Files.getContentUri(VOLUME_NAME); 
    Cursor ca = cr.query(mediaUri, new String[] { MediaStore.MediaColumns._ID }, MediaStore.MediaColumns.DATA + "=?", new String[] {path}, null); 
    if (ca != null && ca.moveToFirst()) { 
     int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID)); 
     ca.close(); 
     return MediaStore.Files.getContentUri(VOLUME_NAME,id); 
    } 
    ca.close(); 
    return null; 
} 
0

最简单,从文件创建内容乌里content://稳健的方法是使用FileProvider。 Uri提供的FileProvider也可以用来提供Uri与其他应用程序共享文件。要从File的绝对路径获取文件Uri,可以使用DocumentFile。fromFile(新文件(路径,名称)),它在Api 22中添加,并在以下版本中返回null。

File imagePath = new File(Context.getFilesDir(), "images"); 
File newFile = new File(imagePath, "default_image.jpg"); 
Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);