Test Script

Tuesday, May 14, 2013

Fetch Image from Camera or Gallery - Android

Hi guys, in this tutorial I will be showing how to get an Image from the user's Camera or from his gallery.

Let's get started :


================================================================
MainActivity.java
================================================================

package com.example.gallerytestapp;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.DragEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

  Uri selectedImageUri;
  String  selectedPath;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  Button b = (Button) findViewById(R.id.bGallery);
  Button bCam= (Button) findViewById(R.id.bCamera);
  ImageView preview = findViewById(R.id.preview);
  bCam.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                startActivityForResult(cameraIntent, 100); 
   }
  });
  
  
  b.setOnClickListener(new OnClickListener() {
  
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
     openGallery(10);
   }
  });
 }
 
 
 
 public void openGallery(int req_code){

        Intent intent = new Intent();

        intent.setType("image/*");

        intent.setAction(Intent.ACTION_GET_CONTENT);

        startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);

   }

public void onActivityResult(int requestCode, int resultCode, Intent data) {



        if (resultCode == RESULT_OK) {
         if(data.getData() != null){
           selectedImageUri = data.getData();
         }else{
          Log.d("selectedPath1 : ","Came here its null !");
          Toast.makeText(getApplicationContext(), "failed to get Image!", 500).show();
         }
         
         if (requestCode == 100 && resultCode == RESULT_OK) {  
                Bitmap photo = (Bitmap) data.getExtras().get("data"); 
                selectedPath = getPath(selectedImageUri);
                preview.setImageURI(selectedImageUri);
                Log.d("selectedPath1 : " ,selectedPath);

            } 
         
            if (requestCode == 10)

            {

               selectedPath = getPath(selectedImageUri);
               preview.setImageURI(selectedImageUri);
               Log.d("selectedPath1 : " ,selectedPath);

            }

        }

    }


 public String getPath(Uri uri) {

        String[] projection = { MediaStore.Images.Media.DATA };

        Cursor cursor = managedQuery(uri, projection, null, null, null);

        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        cursor.moveToFirst();

        return cursor.getString(column_index);

    }
 
}
================================================================


Whoa ! That was a bit long code ! So let me quickly explain what i am doing above :


I have just created a Activity , the layout file has just two buttons & a ImageView. One button is to pick an Image from Gallery , the other button is to use the camera of the device to click a picture.

1) In onClick of the button bCam(which starts the native Camera) i create a intent with the following action "android.provider.MediaStore.ACTION_IMAGE_CAPTURE" This is used to invoke the native Camera of the device.

2) Then i start the activity but call it using " startActivityForResult(cameraIntent, 100); " . This is used when you want a result from the activity you are calling.

3) The startActivityForResult method takes in a intent & a request code.

4) The request code is used to identify the result.

5) The result we receive from the Camera is a image Uri. 

6) To get the result we Override onActivityResult method 

7) This method gets request code, result code & a intent as parameters.

8) We check whether the Result Code is equal to 200 , this means the operation was successful . And also check whether the request code is the same as we had specified.

9) We then take the data returned from the Activity.

10) The imageUri returned is set to the ImageView. This shows the captured image as in the imageView.

================================================================

That was how we fetch a image from the Camera , lets see how to fetch an existing image from the Gallery :

================================================================

1) The other button b is used to open up the gallery 

2) Here we call the method openGallery() passing in a Request Code.

3) In the openGallery() method we create a new intent and set its type to image

4) We set the Action to GET_CONTENT & start the activity.

5) We have to again use the startActivityForResult method here so that we get the result after picking the image from the gallery.

6) Now Gallery is opened,once the user selects a image that image is returned again and set in the imageView.

================================================================

You notice there is one more method i.e. getPath(Uri uri), this method is used to fetch the actual path of the image which the user has selected. This is used when you want to upload the selected image to a server or need the complete file path of the selected Image.

In that method all we are doing is querying the MediaStore to get the actual file-path.


So, thats all from me for this tutorial! As always feel free to drop me a mail or comment below if you have any queries.

UA-42774700-1 Twitter Bird Gadget