In Android applications, it can be useful to offer users the possibility to pick an image from their Gallery. When image is picked, you can then use it in a wallpaper for example or to work on the image depending the purpose of your application.

To achieve that, you must first launch the intent ACTION_PICK to let OS prompt dialog to users to pick an image from Gallery :


public static final int IMAGEREQUESTCODE = 8242008;

// ...

private void pickImageFromGallery() {
  Intent galleryIntent = new Intent(Intent.ACTION_PICK,
    MediaStore.Images.Media.INTERNAL_CONTENT_URI);
  startActivityForResult(galleryIntent, IMAGEREQUESTCODE);
}

When you call pickImageFromGallery, users will see the following dialog on his screen :

Screenshot_2015-01-12-18-38-59
OS prompt a dialog to users to let them choose applications that they want to use to pick an image from Gallery.

Once user have picked an image from Gallery, OS returns to the calling activity where onActivityResult method is invoked. In this method, you must check that the request code matches well the request code you use when your launch intent. Here, we used the constant IMAGEREQUESTCODE. So, we will have the following code :


@Override
protected final void onActivityResult(final int requestCode,
 final int resultCode, final Intent i) {
  super.onActivityResult(requestCode, resultCode, i);

  if (resultCode == RESULT_OK) {
     switch (requestCode) {
       case IMAGEREQUESTCODE:
         manageImageFromUri(i.getData());
       break;
     }
  } else {
     // manage result not ok !
  }

}

You can notice than we check that result code is OK before to process. Intent passed in parameter has a getData method that lets you to get URI of picked image.

Now, we’re going to use this URI to get Bitmap of the picked image to use in the application. This job is made in manageImageFromUri method :


private void manageImageFromUri(Uri imageUri) {
  Bitmap bitmap = null;

  try {
    bitmap = MediaStore.Images.Media.getBitmap(
      this.getContentResolver(), imageUri);

  } catch (Exception e) {
    // Manage exception ...
  }

  if (bitmap != null) {
    // Here you can use bitmap in your application ...
  }
}

To get bitmap, we use getBitmap method from Media class with content resolver and image URI passed in parameters. Once bitmap is got, you can use it like you want in your application Android.