Cross Platform
Android
iOS

Selecting a Gallery Image

This recipe shows how to read an image from the gallery and display it in an ImageView.

Recipe



  1. Add an ImageView to Main.axml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
     <Button  
        android:id="@+id/myButton"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Pick an image from the gallery"/>
     <ImageView 
        android:id="@+id/myImageView"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"/>            
    </LinearLayout>
    

  2. In an Activity subclass, create an Intent with a MIME type set to “image/*” and an action set to ActionGetContent. Pass the intent to a StartActivityForResult method call.

    button.Click += delegate {                
        var imageIntent = new Intent ();
        imageIntent.SetType ("image/*");
        imageIntent.SetAction (Intent.ActionGetContent);
        StartActivityForResult (
            Intent.CreateChooser (imageIntent, "Select photo"), 0);
    } ;
    

  3. Override OnActivityResult and set the image Uri of the ImageView to the Uri of the selected image.

    
    protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
    {
        base.OnActivityResult (requestCode, resultCode, data);
              
        if (resultCode == Result.Ok) {
            var imageView = 
                FindViewById<ImageView> (Resource.Id.myImageView);
            imageView.SetImageURI (data.Data);
        }
    }
    
  4. The selected image appears on the screen as shown above.

Additional Information

The Data property of the Intent returned to OnActivityResult will contain the Uri of the selected image. We check the result in case the user cancelled the selection.