Get content uri from file path in android

2019-01-01 14:28发布

I know the absolute path of an image (say for eg, /sdcard/cats.jpg). Is there any way to the content uri for this file ?

Actually in my code I download an image and save it at a particular location. In order to set the image in an ImageView currently I open the file using the path, get the bytes and create a bitmap and then set the bitmap in the ImageView. This is a very slow process, instead if I could get the content uri then I could very easily use the method ImageView.setImageUri(uri)

标签: android image
8条回答
旧人旧事旧时光
2楼-- · 2019-01-01 15:17

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.

查看更多
无色无味的生活
3楼-- · 2019-01-01 15:17

Easiest and the robust way for creating Content Uri content:// from a File is to use FileProvider. Uri provided by FileProvider can be used also providing Uri for sharing files with other apps too. To get File Uri from a absolute path of File you can use DocumentFile.fromFile(new File(path, name)), it's added in Api 22, and returns null for versions below.

File imagePath = new File(Context.getFilesDir(), "images");
File newFile = new File(imagePath, "default_image.jpg");
Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
查看更多
登录 后发表回答