First, set a default code to identify Intent
:
private static final int PICK_IMAGE = 11;
Second, call Intent
who will be responsible for presenting the user which application he wants to open the gallery to choose the image:
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);
After putting the above code, you need to overwrite the onActivityResult
of your Activity
, because this method will receive the image of the gallery:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PHOTO && resultCode == Activity.RESULT_OK) {
if (data == null) {
// Nenhuma imagem selecionada...
return;
}
InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
Bitmap b = BitmapFactory.decodeStream(inputStream);
Drawable d = new BitmapDrawable(b);
suaImageView.setImageDrawable(d);
}
}
In the above code we receive the content selected by the user, first of all we test if it is really coming from your gallery call through the variable PICK_PHOTO
, then we transform the InputStream
received into a Bitmap
, and a Bitmap
to Drawable
making it possible to use in your ImageView
.
See more in the links below:
android pick images from gallery
How to create a Drawable from a stream without resizing it?