Getting path from Uri from Google Photos app

前端 未结 2 989
不知归路
不知归路 2021-01-12 16:49

I have an app which allows to select photos with an external app. Then I take the path of the photo from the uri and use it for internal actions.

When user selects a

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 17:13

    Finally and according to @CommonsWare answer and the previous post about this issue I solved getting the InputStream from the uri, coping into a new temporal file and passing the path to the function I need to use.

    Here is the simplificated code:

    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
    }
    

提交回复
热议问题