image - Get content uri from file path in android

ID : 10387

viewed : 58

Tags : androidimageandroid

Top 5 Answer for image - Get content uri from file path in android

vote vote

95

Try with:

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

Or with:

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

80

UPDATE

Here it is assumed that your media (Image/Video) is already added to content media provider. If not then you will not able to get the content URL as exact what you want. Instead there will be file Uri.

I had same question for my file explorer activity. You should know that the contenturi for file only supports mediastore data like image, audio and video. I am giving you the code for getting image content uri from selecting an image from sdcard. Try this code, maybe it will work for you...

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

For support android Q

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()) {         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {             ContentResolver resolver = context.getContentResolver();             Uri picCollection = MediaStore.Images.Media                     .getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);             ContentValues picDetail = new ContentValues();             picDetail.put(MediaStore.Images.Media.DISPLAY_NAME, imageFile.getName());             picDetail.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");             picDetail.put(MediaStore.Images.Media.RELATIVE_PATH,"DCIM/" + UUID.randomUUID().toString());             picDetail.put(MediaStore.Images.Media.IS_PENDING,1);             Uri finaluri = resolver.insert(picCollection, picDetail);             picDetail.clear();             picDetail.put(MediaStore.Images.Media.IS_PENDING, 0);             resolver.update(picCollection, picDetail, null, null);             return finaluri;         }else {             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;     }   } } 
vote vote

73

The accepted solution is probably the best bet for your purposes, but to actually answer the question in the subject line:

In my app, I have to get the path from URIs and get the URI from paths. The former:

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

The latter (which I do for videos, but can also be used for Audio or Files or other types of stored content by substituting MediaStore.Audio (etc) for 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; } 

Basically, the DATA column of MediaStore (or whichever sub-section of it you're querying) stores the file path, so you use that info to look it up.

vote vote

68

// This code works for images on 2.2, not sure if any other media types

   //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();     }    }; 
vote vote

55

You can use these two ways based on use

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

or

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

I have tried both ways and both works.

Top 3 video Explaining image - Get content uri from file path in android

Related QUESTION?