简体   繁体   English

我可以从图像文件的名称中获取Uri吗?

[英]Can I get Uri of image file from its name?

There are some image files, and I want to get Uri of these image files. 有一些图像文件,我想获取这些图像文件的Uri。 In my code, I only know path and file name of image files. 在我的代码中,我只知道图像文件的路径和文件名。 How can I get Uri from its path and file name? 如何从其路径和文件名获取Uri?

If you have a File , you can always convert it to a URI : 如果您有File ,则始终可以将其转换为URI

File file = new File(path + File.pathSeparator + filename);
URI uri = file.toURI();

Or, if you want to use the Android Uri class: 或者,如果您想使用Android Uri类:

Uri uri = Uri.fromFile(file);

I had same question for my file explorer activity...but u should knw tht the contenturi for file only supports the mediastore data like image,audio and video....I am giving you for getting image content uri from selecting an image from sdcard....try this code...may be it will work for you... 我对文件浏览器活动有相同的问题...但是您应该知道文件的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));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + 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;
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM