在Android 10及以上版本中,无法直接从图片URI获取其真实的文件路径。可以使用以下代码示例中的方法,将图片文件先复制到应用程序专有目录的缓存目录中,然后再操作该文件。
private String getFilePathFromUri(Context context, Uri uri) {
String fileName = getFileName(uri);
File cacheDir = context.getCacheDir();
File file = new File(cacheDir, fileName);
try (InputStream inputStream = context.getContentResolver().openInputStream(uri);
OutputStream outputStream = new FileOutputStream(file)) {
byte[] buffer = new byte[4 * 1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
private String getFileName(Uri uri) {
String fileName = "";
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
cursor.close();
}
return fileName;
}