You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从图库获取多张选中图片的真实路径并存储到数组中

获取多张选中图片的真实路径方法

刚好看到你在找怎么批量获取图库选中图片的真实路径,你现在手里的方法只能处理单张,那咱们把它扩展成批量版本就搞定啦~

首先先优化一下你现有的单张路径获取方法——原来的代码里Cursor没关闭,容易造成内存泄漏,我帮你补上了关闭逻辑:

public static String getFileNameByUri(Context context, Uri uri) {
    String fileName = "unknown";// default fileName
    Uri filePathUri = uri;
    Cursor cursor = null;
    try {
        if (uri.getScheme().equals("content")) {
            cursor = context.getContentResolver().query(uri, null, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                filePathUri = Uri.parse(cursor.getString(columnIndex));
                fileName = filePathUri.getLastPathSegment();
            }
        } else if (uri.getScheme().equals("file")) {
            fileName = filePathUri.getLastPathSegment();
        } else {
            fileName = fileName + "_" + filePathUri.getLastPathSegment();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return fileName;
}

接下来就是批量处理的逻辑啦——核心就是遍历你存储图片Uri的数组,对每个Uri调用上面的单张方法,把有效路径收集到List里就行:

public static List<String> getMultipleImagePaths(Context context, List<Uri> imageUriList) {
    List<String> imagePathList = new ArrayList<>();
    if (imageUriList == null || imageUriList.isEmpty()) {
        return imagePathList;
    }
    for (Uri uri : imageUriList) {
        String path = getFileNameByUri(context, uri);
        if (!"unknown".equals(path)) {
            imagePathList.add(path);
        }
    }
    return imagePathList;
}

最后还有几个要注意的点:

  • 权限要到位:Android 6.0及以上需要在运行时申请READ_EXTERNAL_STORAGE权限,Manifest里也要先声明这个权限;
  • Android 10+适配:从Android 10开始,系统限制了直接访问MediaStore.Images.Media.DATA字段,如果你要适配高版本系统,建议用ContentResolver.openInputStream()来读取图片内容。如果一定要拿路径,可以试试MediaStore.setRequireOriginal(uri)或者按照分区存储的规则来处理。

内容的提问来源于stack exchange,提问作者epssy_sy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:18:49