当前位置: 首页 > 知识库问答 >
问题:

如何使用uri而不使用mediastore.images.media.data获取图像真实路径

马浩淼
2023-03-14

我发现mediastore.images.media.data不推荐使用,所以我想用另一种方法获取图像的真实路径。

这里是我获得图像的uri和标题的新方法,但我不知道如何获得真实的路径。

打印uri、标题、路径:

Photouri:内容://Media/External/Images/Media/1605

标题:IMG_20191223143418

但我只想要这样:/storage/emulated/0/dcim/1733/img_20191223143418.jpg

public static String getRealPathFromUri(Context context, Uri uri) throws IOException {

    String filePath = null;

    if (DocumentsContract.isDocumentUri(context, uri)) {

                String documentId = DocumentsContract.getDocumentId(uri);
                if (isMediaDocument(uri)) { // MediaProvider.
                    String id = documentId.split(":")[1];

                    String selection = MediaStore.Images.Media._ID + "=?";
                    String[] selectionArgs = {id};

                    filePath = getDataColumnImage(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
                } else if (isDownloadsDocument(uri)) { // DownloadsProvider.
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                    filePath = getDataColumnImage(context, contentUri, null, null);
                }
        }
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            filePath = getDataColumnImage(context, uri, null, null);
        }
        else if ("file".equals(uri.getScheme())) {
            filePath = uri.getPath();
        }else
            return filePath = null;
        return filePath;
}


private static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

private static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

private static String getDataColumnImage(Context context, Uri uri, String selection, String[] selectionArgs) {

    String path = null;

    String[] projection = new String[]{
                MediaStore.Files.FileColumns._ID,
                MediaStore.Images.Media.DATE_TAKEN,
                MediaStore.Images.Media.WIDTH,
                MediaStore.Images.Media.HEIGHT,
                MediaStore.MediaColumns.TITLE,
                MediaStore.Images.Media.MIME_TYPE,
        };
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(
                    uri,
                    projection,
                    selection,
                    selectionArgs,
                    null
            );
            if (cursor != null && cursor.moveToFirst()) {
                int idColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID);
                int titleColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.TITLE);

                Uri photoUri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cursor.getString(idColumn));
                String title = cursor.getString(titleColumn);

                Log.e("TAG", "photoUri: " + photoUri);
                Log.e("TAG", "title: " + title);
                Log.e("TAG", "photoUri.getPath: " + photoUri.getPath());
            }
        } catch (Exception e) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return path;

        // MediaStore.Images.Media.DATA is deprecated, so I want to use the other way as mentioned above to get real path.
        /*String[] projection = new String[]{MediaStore.Images.Media.DATA};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                    path = cursor.getString(columnIndex);
                }
            } catch (Exception e) {
                if (cursor != null) {
                    cursor.close();
                }
            }
            return path;*/
}

共有1个答案

长孙翔
2023-03-14

只需使用此方法getImagePath();公共类RealPathUtil{

@SuppressLint("NewApi")
private static String getRealPathApi19Above(Context context, Uri uri) {
    String filePath = "";
    try {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }


      /*  String wholeID = DocumentsContract.getDocumentId(uri);

        // Split at colon, use second item in the array
        String id = wholeID.split(":")[1];

        String[] column = {MediaStore.Images.Media.DATA};

        // where id is equal to
        String sel = MediaStore.Images.Media._ID + "=?";

        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                column, sel, new String[]{id}, null);

        int columnIndex = cursor.getColumnIndex(column[0]);

        if (cursor.moveToFirst()) {
            filePath = cursor.getString(columnIndex);
        }
        cursor.close();
        */

    } catch (Exception e) {
        filePath = "";
    }
    return filePath;
}


public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


@SuppressLint("NewApi")
private static String getRealPathApi11to18(Context context, Uri contentUri) {
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        String result = null;

        CursorLoader cursorLoader = new CursorLoader(
                context,
                contentUri, proj, null, null, null);
        Cursor cursor = cursorLoader.loadInBackground();

        if (cursor != null) {
            int column_index =
                    cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            result = cursor.getString(column_index);
        }
        return result;
    } catch (Exception e) {
        return "";
    }
}


public static String getImagePath(Context context, Uri uri) {
    if (Build.VERSION.SDK_INT < 19)
        return getRealPathApi11to18(context, uri);
    else
        return getRealPathApi19Above(context, uri);

} public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is Google Photos.
 */
public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
 类似资料:
  • 如何获取相机捕获的原始图像的路径或uri。当我使用下面的代码时,它会返回google文档中提到的原始图像的缩略图。我想要原始图像的路径或uri。 我使用了以下代码,但它返回一个缩略图。

  • 问题内容: 我是Android开发的新手,正在使用JSON解析方法解析数据,使用List Fragment扩展了类,并且希望将数据显示在列表视图中,但是问题是除图像外,我获取的所有数据都非常完美,我没有不知道该怎么解决,我的回答是这样的 问题答案: 尝试使用自定义适配器的AndroidQuery: 如何将适配器设置为ListView:

  • 在预处理之后,这就是我如何将它发送到Tesseract OCR 但是OCR'ed是空的。 编辑: 此图像是PDF的一部分。将PDF转换为jpg,然后再次加载,然后通过给出BB坐标来裁剪此部分。 但是它打印的OCR'ed输出仍然关闭:

  • 我有一个表单,在那里,我想使用图像而不是单选按钮。我如何显示多个图像,而不是单选按钮。例如,性别与“男性” 但在这里,问题出现了,当我将输入id更改为其他名称时,它不起作用。有人能帮我吗,因为这是一个非常简单的方法,我想用这个。您可以将输入id更改为“visa1”,然后查看结果。

  • 我对nohup命令有意见。 当我运行我的工作时,我有很多数据。输出nohup.out变得太大,我的进程会变慢。我如何运行这个命令而不得到nohup.out?

  • 问题内容: 如何使用PIL检测PNG图像是否具有透明的Alpha通道? 通过上面的代码,我们知道PNG图像是否不具有Alpha通道,但是如何获得Alpha值? 我没有在PIL网站上描述的img.info词典中找到“透明”键 我正在使用Ubuntu和zlib1g,已经安装了zlibc软件包。 问题答案: 要获取RGBA图像的alpha层,您需要做的是: 要么 有一种设置Alpha层的方法: 透明度键