How To Pick Image From Gallery in Android App

Since few days I am working on an Android app and learning all the nitty gritty of its APIs. I will share few How-to stuffs that we frequently require in Android.

To start with let us see how to integrate Image Gallery with your App. Consider a requirement, you want your app user to select Image from the Gallery and use that image to do some stuff. For example, in Facebook app you can select Picture from your phone and upload directly to your profile.

Let us create an example with following requirement:

  1. First screen shows user with and Image view and a button to loan Picture.
  2. On click of “Load Picture” button, user will be redirected to Android’s Image Gallery where she can select one image.
  3. Once the image is selected, the image will be loaded in Image view on main screen.

So lets start.

Step 1: Create Basic Android Project in Eclipse

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as ImageGalleryDemo and select Android Runtime 2.1 or sdk 7.

Once you are done with above steps, you will have a basic hello world Android App.

Step 2: Change the Layout

For our demo, we need simple layout. One Image view to display user selected image and one button to trigger Image gallery.

Open layout/main.xml in your android project and replace its content with following:

File: res/layout/main.xml

<?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">
	<ImageView
		android:id="@+id/imgView"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:layout_weight="1"></ImageView>
	<Button 
		android:id="@+id/buttonLoadPicture" 
		android:layout_width="wrap_content" 
		android:layout_height="wrap_content" 
		android:layout_weight="0" 
		android:text="Load Picture" 
		android:layout_gravity="center"></Button>
</LinearLayout>

So our Android’s app UI is very simple, One LinearLayout to organize Image view and Button linearly. Note that the id of Image view is imgView and that of Button is buttonLoadPicture.

Step 3: Android Java Code to trigger Image Gallery Intent

We now need to write some Java code to actually handle the button click. On click of buttonLoadPicture button, we need to trigger the intent for Image Gallery.

Thus, on click of button we will trigger following code:

	Intent i = new Intent(
	Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
	
	startActivityForResult(i, RESULT_LOAD_IMAGE);

Note how we passed an integer RESULT_LOAD_IMAGE to startActivityForResult() method. This is to handle the result back when an image is selected from Image Gallery.

So the above code will trigger Image Gallery. But how to retrieve back the image selected by user in our main activity?

Step 4: Getting back selected Image details in Main Activity

Once user will select an image, the method onActivityResult() of our main activity will be called. We need to handle the data in this method as follows:

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
						
			// String picturePath contains the path of selected Image
		}

Note that method onActivityResult gets called once an Image is selected. In this method, we check if the activity that was triggered was indeed Image Gallery (It is common to trigger different intents from the same activity and expects result from each). For this we used RESULT_LOAD_IMAGE integer that we passed previously to startActivityForResult() method.

Final Code

Below is the final code of ImageGalleryDemoActivity class.

package net.viralpatel.android.imagegalleray;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class ImageGalleryDemoActivity extends Activity {
    
	
	private static int RESULT_LOAD_IMAGE = 1;
	

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				Intent i = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				
				startActivityForResult(i, RESULT_LOAD_IMAGE);
			}
		});
    }
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
			
			ImageView imageView = (ImageView) findViewById(R.id.imgView);
			imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
		
		}
    
    
    }
}

Screen shots of Android app

First screen: Lets user to trigger Image Gallery
android-gallery-intent-example

User can select an image from Image Gallery
android-gallery-intent-select-image

Once user selects an image, the same will be displayed on our main activity
android-gallery-intent-example-demo

Download Source Code

ImageGalleryDemo.zip (46 KB)



71 Comments

  • Rajeshwar 23 October, 2013, 12:38

    I am opening an image in gallery app for Android 4.1.The gallery opens but it returns only that particular image. I am unable to scroll the images in gallery. I want my gallery to function similiar to how myfiles works when we open an image from Myfiles

  • zero0ne 1 November, 2013, 12:50

    Hello,
    if i load many image from my server?

    Regards.

  • samra 12 November, 2013, 20:38

    hi i face an error…………………when i select the image it can show force close msg on screen

  • Hardz 23 December, 2013, 18:55

    Thanks… For this use full code …
    using your code i am try to pick image from gallary but when i select an image then my activity is shows me “Unfortunately, my photo effect has stopped” .
    give me solution for it as soon as possible .

  • Zoe 23 December, 2013, 22:12

    Hi, if I have the button before the image view then it doesn’t work it just forces close. I was just wondering why this was?

  • Dalveer singh 24 December, 2013, 12:27

    plz send code how to pic from image view

  • AJay 28 December, 2013, 14:03

    your code is good but you can simply use setImageURI(uri) to set to image to imageview then why you use cursor ?
    can you please explain this….

  • Tanuj 17 January, 2014, 19:03

    I am using Robotium and I want to pick image from library/gallery. How should I achieve it. I have read-write permission to sdcard.

  • James 22 February, 2014, 22:51

    Hey.

    Thanks for the tutorial. I just wanted to offer a suggestion for you in the future. I would add javadoc comments to the code you are developing. It makes it a lot easier for “us” to understand the code in the tutorial, and it offers you some insight into your code when you come back to it after an extended period of time.

    Also, it’s just good practice to document your code.

    Just a suggestion ;)

    Thanks for this tutorial though. If I wanted to use this with an application I would use a database column to save the image so that it is there whenever the user loads the app. What would be the best practice for this? Would it be just a matter of storing the string with the path directory?

  • nida 2 March, 2014, 20:18

    Hi…plz help i wana do profile form on android whic s similar in whtsapp.so plz hel me….

  • Rolando Mirabal H. (@rolandomirabalh) 1 April, 2014, 2:53

    thank you very much!!! it worked like a blast

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]