从Google照片应用中获取Uri的路径

ada*_*aRi 7 android uri

我有一个应用程序,允许使用外部应用程序选择照片.然后我从uri拍摄照片的路径并将其用于内部动作.

当用户使用Google Photo选择照片时,如果图片是本地存储的,则下一个代码可以正常工作.但是如果图片在云中,则cursor.getString(index)的结果为null.

我搜索了一些信息,但不确定解决方案

final String[] projection = { "_data" };
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);

if (cursor != null && cursor.moveToFirst()) {
    final int index = cursor.getColumnIndexOrThrow("_data");
    return cursor.getString(index);
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

ada*_*aRi 14

最后,根据@CommonsWare的回答和之前关于这个问题的帖子,我解决了从uri获取InputStream,处理新的临时文件并将路径传递给我需要使用的函数.

这是简化的代码:

public String getImagePathFromInputStreamUri(Uri uri) {
    InputStream inputStream = null;
    String filePath = null;

    if (uri.getAuthority() != null) {
        try {
            inputStream = getContentResolver().openInputStream(uri); // context needed
            File photoFile = createTemporalFileFrom(inputStream);

            filePath = photoFile.getPath();

        } catch (FileNotFoundException e) {
            // log
        } catch (IOException e) {
            // log
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return filePath;
}

private File createTemporalFileFrom(InputStream inputStream) throws IOException {
    File targetFile = null;

    if (inputStream != null) {
        int read;
        byte[] buffer = new byte[8 * 1024];

        targetFile = createTemporalFile();
        OutputStream outputStream = new FileOutputStream(targetFile);

        while ((read = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, read);
        }
        outputStream.flush();

        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return targetFile;
}

private File createTemporalFile() {
    return new File(getExternalCacheDir(), "tempFile.jpg"); // context needed
}
Run Code Online (Sandbox Code Playgroud)