This question was originally asked for Android 1.6.
I am working on photos options in my app.
I have a button and an ImageView in my Activity. When I click the button it would redirect to the gallery and I would be able to select an image. The selected image would appear in my ImageView.
call chooseImage method like-
Updated answer, nearly 5 years later:
The code in the original answer no longer works reliably, as images from various sources sometimes return with a different content URI, i.e.
content://
rather thanfile://
. A better solution is to simply usecontext.getContentResolver().openInputStream(intent.getData())
, as that will return an InputStream that you can handle as you choose.For example,
BitmapFactory.decodeStream()
works perfectly in this situation, as you can also then use the Options and inSampleSize field to downsample large images and avoid memory problems.However, things like Google Drive return URIs to images which have not actually been downloaded yet. Therefore you need to perform the getContentResolver() code on a background thread.
Original answer:
The other answers explained how to send the intent, but they didn't explain well how to handle the response. Here's some sample code on how to do that:
After this, you've got the selected image stored in "yourSelectedImage" to do whatever you want with. This code works by getting the location of the image in the ContentResolver database, but that on its own isn't enough. Each image has about 18 columns of information, ranging from its filepath to 'date last modified' to the GPS coordinates of where the photo was taken, though many of the fields aren't actually used.
To save time as you don't actually need the other fields, cursor search is done with a filter. The filter works by specifying the name of the column you want, MediaStore.Images.Media.DATA, which is the path, and then giving that string[] to the cursor query. The cursor query returns with the path, but you don't know which column it's in until you use the
columnIndex
code. That simply gets the number of the column based on its name, the same one used in the filtering process. Once you've got that, you're finally able to decode the image into a bitmap with the last line of code I gave.Start intent
Process result
Alternatively, you can also downsample your image to avoid OutOfMemory errors.
Do this to launch the gallery and allow the user to pick an image:
Then in your
onActivityResult()
use the URI of the image that is returned to set the image on your ImageView.You have to start the gallery intent for a result.
Then in
onActivityForResult
, callintent.getData()
to get the Uri of the Image. Then you need to get the Image from the ContentProvider.