Getting path from Uri from Google Photos app

前端 未结 2 986
不知归路
不知归路 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:07

    When user selects a photo with Google Photo, if the picture is locally stored then the next code works perfectly.

    Not necessarily. There is no requirement for that Uri to respond with a _data column to a query(). There is no requirement for the value it returns to be useful to you (e.g., a file on internal storage or removable storage that you cannot access).

    If you need the photo loaded into an ImageView, pass the Uri to an image-loading library, such as Picasso.

    If you need the bytes of the photo, use openInputStream() with ContentResolver to get an InputStream on the content identified by the Uri. Please open and read from the InputStream on a background thread.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题