Skip to content
Advertisement

How to display an image from the Gallery in an ImageView?

I created a button that lets the user choose between “Take picture with camera” and “Select picture from gallery”.

When the picture is taken/chosen, I then display it in an ImageView of the next activity which I do by passing the URI of the file created to store the taken/selected picture.

It works as expected when the user takes a picture with his camera but when he selects an image from gallery, no image is shown in the next activity despite both intents (take a picture and select a picture) being coded the same.

My question(s): Why isn’t the image displayed in the next activity ONLY when picked from the gallery ? Or how should I proceed to display it ?

Intent to open camera (working fine):

JavaScript

Intent to access gallery and pick an image:

JavaScript

Then here’s the onActivityResult: (currentPhotoPath is the absolute path of the file created to store the image)

JavaScript

Below is how the image is displayed in the following activity:

JavaScript

I made sure to have the READ_EXTERNAL_STORAGE in the manifest and the xml layout is just set to “match_parent” for height and width but I can add them if it’s relevant.

Advertisement

Answer

Few Intent actions use EXTRA_OUTPUT. Mostly, that is an ACTION_IMAGE_CAPTURE thing.

More typically, an Intent for getting a piece of content (ACTION_PICK, ACTION_GET_CONTENT, ACTION_OPEN_DOCUMENT, ACTION_CREATE_DOCUMENT, ACTION_OPEN_DOCUMENT_TREE, etc.) return a Uri from the content supplier in the Intentdelivered toonActivityResult(). Given your implementation, that would be data.getData()to get thatUri`.

You can then use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. In your case, for example, you could use that InputStream to copy the bytes to a FileOutputStream to make your own local copy of the content.

Note that you only have short-term access to the content identified by the Uri.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement