Android: How to set the photo selected from gallery to a bitmap

Kinoscorpia picture Kinoscorpia · Apr 22, 2015 · Viewed 26.5k times · Source

I am asking the user for the access to the gallery through the code as a listener here:

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);

However, I am confused as to how I would set a variable to the photo selected.

Where would I put the code to set a variable as the photo selected?

Thanks :)

Answer

Akash picture Akash · Apr 22, 2015

First you have to override onActivityResult to get the uri of the file selected image

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == SELECT_PHOTO) {

        if (resultCode == RESULT_OK) {
            if (intent != null) {
                // Get the URI of the selected file
                final Uri uri = intent.getData();
                useImage(uri);                   
              }
        }
       super.onActivityResult(requestCode, resultCode, intent);

    }
}

Then define useImage(Uri) to use the image

void useImage(Uri uri)
{
 Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
 //use the bitmap as you like
 imageView.setImageBitmap(bitmap);
}