How to pick an image from Image Gallery

Today we are going to show you how easy it is to read an image from the Image Gallery and use it in your Android application. This tutorial was requested by Nora on our Forum pagehttp://www.itcuties.com/answers/how-to-attach-photo-in-my-app.
Our application looks like this:

ITCuties - Android Pick Image from Gallery - The base view

ITCuties – Android Pick Image from Gallery – The base view

ITCuties - Android Pick Image from Gallery - Gallery Image view

ITCuties – Android Pick Image from Gallery – Gallery Image view

ITCuties - Android Pick Image from Gallery - Picked Image view

ITCuties – Android Pick Image from Gallery – Picked Image view

What our application does is, when You click on the Button then the Image Gallery Intent is started which gives you ability to pick an image stored on your phone. Next, when you pick an image it is displayed under the button. Simple ?! :)

Here is the code of this application’s layout. It’s simple. It consist of Button and ImageView components.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SelectImageActivity" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="15dp"
        android:text="@string/pick_button" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

Next we have our activity code. Watch our video (above) to see how does it work.

package com.itcuties.apps.itcpickgalleryimageapp;

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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

/**
 * This activity displays the gallery image picker. 
 * It displays the image that was picked.
 * 
 * @author ITCuties
 *
 */
public class SelectImageActivity extends Activity implements OnClickListener {

	// Image loading result to pass to startActivityForResult method.
	private static int LOAD_IMAGE_RESULTS = 1;
	
	// GUI components
	private Button button;	// The button
	private ImageView image;// ImageView
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_image);
		
		// Find references to the GUI objects
		button = (Button)findViewById(R.id.button);
		image = (ImageView)findViewById(R.id.image);
		
		// Set button's onClick listener object.
		button.setOnClickListener(this);
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		// Here we need to check if the activity that was triggers was the Image Gallery.
		// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
		// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
		if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
			// Let's read picked image data - its URI
			Uri pickedImage = data.getData();
			// Let's read picked image path using content resolver
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
            cursor.moveToFirst();
            String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
            
            // Now we need to set the GUI ImageView data with data read from the picked file.
            image.setImageBitmap(BitmapFactory.decodeFile(imagePath));
            
            // At the end remember to close the cursor or you will end with the RuntimeException!
            cursor.close();
		}
	}
	
	@Override
	public void onClick(View v) {
		// Create the Intent for Image Gallery.
		Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		
		// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
        startActivityForResult(i, LOAD_IMAGE_RESULTS);
	}
}

Download this sample code here.

This code is available on our GitHub repository as well.

2 Responses to "How to pick an image from Image Gallery"

  1. sarbjot says:

    THANKS FOR HELPING US…

    Reply
  2. Alma666 says:

    Hi, thanks for your tutorial.
    One question,may I leave the selected image from the gallery as default image? When reopen the app, the image still appear load on the imageview, until I select other image.
    Sorry my bad english!!!
    Tu hablas español??? Saludos desde Chile.

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>