我知道图像的绝对路径(例如,/sdcard/cats.jpg)。是否有任何方法获得这个文件的内容uri ?
实际上,在我的代码中,我下载了一张图像并将其保存在特定的位置。为了在ImageView实例中设置图像,目前我使用路径打开文件,获取字节并创建位图,然后在ImageView实例中设置位图。这是一个非常缓慢的过程如果我能得到内容uri那么我就可以很容易地使用imageview。setimageuri (uri)方法
我知道图像的绝对路径(例如,/sdcard/cats.jpg)。是否有任何方法获得这个文件的内容uri ?
实际上,在我的代码中,我下载了一张图像并将其保存在特定的位置。为了在ImageView实例中设置图像,目前我使用路径打开文件,获取字节并创建位图,然后在ImageView实例中设置位图。这是一个非常缓慢的过程如果我能得到内容uri那么我就可以很容易地使用imageview。setimageuri (uri)方法
当前回答
//此代码适用于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();
}
};
其他回答
你可以根据使用情况来使用这两种方法
Uri Uri = Uri。解析(“字符串文件位置”);
or
类型 type = Type.fromFile(new File(“string file location”));
两种方法我都试过了,结果都有效。
试一试:
ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));
或:
ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));
//此代码适用于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();
}
};
虽然已经晚了,但将来可能会对别人有所帮助。
要获取文件的内容URI,您可以使用以下方法:
FileProvider。getUriForFile(上下文上下文,字符串权限,文件文件)
它返回内容URI。
看看这个来学习如何设置一个FileProvider
从文件创建Content Uri内容://最简单、最健壮的方法是使用FileProvider。FileProvider提供的Uri也可以用于与其他应用程序共享文件。要从File的绝对路径获取File Uri,你可以使用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);