Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to Select an Image from Gallery in Android?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Selecting an image from a gallery in Android is required when the user has to upload or set their image as a profile picture or the user wants to send a pic to the other. So in this article, it’s been discussed step by step how to select an image from the gallery and preview the selected image. Have a look at the following image what’s been discussed further in this article.

Select an Image from Gallery in Android

Steps to implement image selection from the gallery

Step 1: Create an empty activity project

Step 2: Working with the activity_main.xml

  • The main layout of the application includes one button to open the image selector, and one Image View to preview the selected image from the gallery.
  • To implement the layout of the application, invoke the following code inside the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">
 
    <!--Button to open the image selector-->
    <Button
        android:id="@+id/BSelectImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp"
        android:backgroundTint="@color/colorPrimary"
        android:text="SELECT IMAGE"
        android:textColor="@android:color/white"
        android:textSize="18sp" />
 
    <!--ImageView to preview the selected image-->
    <ImageView
        android:id="@+id/IVPreviewImage"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_below="@id/BSelectImage"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp" />
 
</RelativeLayout>


 Output UI:

Step 3: Working with the MainActivity.java file 

  • In this case, the imageChooser is triggered with the intent of the type “image” and action as ACTION_GET_CONTENT.
  • Invoke the following code to implement the same. Comments are added for better understanding.

Example

Java




import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
 
public class MainActivity extends AppCompatActivity {
 
    // One Button
    Button BSelectImage;
 
    // One Preview Image
    ImageView IVPreviewImage;
 
    // constant to compare
      // the activity result code
    int SELECT_PICTURE = 200;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // register the UI widgets with their appropriate IDs
        BSelectImage = findViewById(R.id.BSelectImage);
        IVPreviewImage = findViewById(R.id.IVPreviewImage);
 
        // handle the Choose Image button to trigger
          // the image chooser function
        BSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageChooser();
            }
        });
    }
 
    // this function is triggered when
      // the Select Image Button is clicked
    void imageChooser() {
 
        // create an instance of the
          // intent of the type image
        Intent i = new Intent();
        i.setType("image/*");
        i.setAction(Intent.ACTION_GET_CONTENT);
 
        // pass the constant to compare it
          // with the returned requestCode
        startActivityForResult(Intent.createChooser(i, "Select Picture"), SELECT_PICTURE);
    }
 
    // this function is triggered when user
      // selects the image from the imageChooser
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
 
        if (resultCode == RESULT_OK) {
 
            // compare the resultCode with the
              // SELECT_PICTURE constant
            if (requestCode == SELECT_PICTURE) {
                // Get the url of the image from data
                Uri selectedImageUri = data.getData();
                if (null != selectedImageUri) {
                    // update the preview image in the layout
                    IVPreviewImage.setImageURI(selectedImageUri);
                }
            }
        }
    }
}


 Output: Run on Emulator

Alternative Code: In case: startActivityForResult is deprecated

Java




private void imageChooser()
{
    Intent i = new Intent();
    i.setType("image/*");
    i.setAction(Intent.ACTION_GET_CONTENT);
 
    launchSomeActivity.launch(i);
}
 
ActivityResultLauncher<Intent> launchSomeActivity
    = registerForActivityResult(
        new ActivityResultContracts
            .StartActivityForResult(),
        result -> {
            if (result.getResultCode()
                == Activity.RESULT_OK) {
                Intent data = result.getData();
                // do your operation from here....
                if (data != null
                    && data.getData() != null) {
                    Uri selectedImageUri = data.getData();
                    Bitmap selectedImageBitmap;
                    try {
                        selectedImageBitmap
                            = MediaStore.Images.Media.getBitmap(
                                this.getContentResolver(),
                                selectedImageUri);
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                    imageView.setImageBitmap(
                        selectedImageBitmap);
                }
            }
        });


 


My Personal Notes arrow_drop_up
Last Updated : 17 May, 2022
Like Article
Save Article
Similar Reads
Related Tutorials