【问题标题】:Can I get Uri of image file from its name?我可以从其名称中获取图像文件的 Uri 吗?
【发布时间】:2010-02-01 04:54:26
【问题描述】:

有一些图像文件,我想获取这些图像文件的 Uri。 在我的代码中,我只知道图像文件的路径和文件名。 如何从其路径和文件名中获取 Uri?

【问题讨论】:

    标签: android


    【解决方案1】:

    如果您有File,您可以随时将其转换为URI

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

    或者,如果您想使用 Android Uri 类:

    Uri uri = Uri.fromFile(file);
    

    【讨论】:

    • 谢谢。实际上,我正在寻找 Uri 而不是 URI,但它们几乎相同,所以我可以找到解决方案。
    • 啊,我不知道你的意思是 Android 特定的 Uri 类。我已经更新了我的答案以包含它。
    【解决方案2】:

    我的文件浏览器活动有同样的问题...但是您应该知道文件的 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));
                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;
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-21
      • 2014-03-06
      • 1970-01-01
      相关资源
      最近更新 更多