简体   繁体   English

如何在android 10及更高版本的android中获取捕获图像和图库图像的真实路径

[英]How to get real path of capture image and gallery image in android in android 10 and above

for getting the real path of capture image and gallery image the following code work perfectly fine for me.为了获得捕获图像和图库图像的真实路径,以下代码对我来说非常好。

private String getRealPathFromURI(Uri contentUri) {
        String result = null;
        try{
            String[] proj = { MediaStore.Images.Media.DATA };
            CursorLoader loader = new CursorLoader(requireActivity(), contentUri, proj, null, null, null);
            Cursor cursor = loader.loadInBackground();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            result = cursor.getString(column_index);
            cursor.close();
        }catch(Exception e){
            Log.i("error_getting_path",e.getMessage());
        }

        return result;
    }

but in android 10 and above device i am not able to get the path of capture and gallery image .但在 android 10 及更高版本的设备中,我无法获得捕获路径和图库图像。 so my app is not working in android 10 and above for this feature.所以我的应用程序无法在 android 10 及更高版本中使用此功能。 please suggest the best way to get path in all android devices.请建议在所有 android 设备中获取路径的最佳方法。

  private static String getRealPathFromURI(Uri uri) {
    Uri returnUri = uri;
    Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);
    int nameIndex = returnCursor.getColumnIndex( OpenableColumns.DISPLAY_NAME);

    returnCursor.moveToFirst();
    String name = (returnCursor.getString(nameIndex));

    File file = new File(context.getFilesDir(), name);
    try {
        InputStream inputStream = context.getContentResolver().openInputStream(uri);
        FileOutputStream outputStream = new FileOutputStream(file);
        int read = 0;
        int maxBufferSize = 1 * 1024 * 1024;
        int bytesAvailable = inputStream.available();

      
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);

        final byte[] buffers = new byte[bufferSize];
        while ((read = inputStream.read(buffers)) != -1) {
            outputStream.write(buffers, 0, read);
        }
      
        inputStream.close();
        outputStream.close();
        Log.e("File Path", "Path " + file.getAbsolutePath());

    } catch (Exception e) {
        Log.e("Exception", e.getMessage());
    }
    return file.getAbsolutePath();
}

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

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