Picture Selection from Camera & Gallery

Hello Guys,
I am here after long time and today i am posting one new sample.

Today I have build simple example in which you can select either Camera or Gallery to pick up an image.For that you have to simple click on Default image and that will launch dialog to ask selection alternative Camera / Gallery.

You can choose any one of them and pick up single image form respective item index either it could be Camera or Gallery.

I will upload next sample in which you can select multiple images from Gallery and use that path.

One Major thing that i have use here and that is Copy Image to your own created Folder. It means when you Capture any image from Camera or Gallery that image will be copied and pasted into your specific /DIR and we will use that image path from target /dir.

So, You can save and safe your images in your own directory.

Now What you will learn from this post ?

  • How to Capture image from camera in android ?
  • How to Pick up  image from Gallery in android ?
  • How to launch alert dialog for image selection either Camera & Gallery ?
  • How to create folder in SD Card ?
  • How to copy image at specific folder in SD Card ?
  • How to create Random File name for image ?
  • How to set Header & Footer fix view using Linear Layout in android ?

Let start with XML layout. (I will show only major code here)


android:orientation="vertical" >

android:src="@drawable/user_logo" />

Image Selection Mode Camera or Gallery Dialog 

– After the selection of one of the mode you will get either Camera screen or Gallery screen , Here you have to select any single image.

– If you are not selecting any image then result should be blank.

public void Image_Picker_Dialog()
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Pictures Option");
myAlertDialog.setMessage("Select Picture Mode");

myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener()
public void onClick(DialogInterface arg0, int arg1)
Utility.pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
Utility.pictureActionIntent.putExtra("return-data", true);
startActivityForResult(Utility.pictureActionIntent, Utility.GALLERY_PICTURE);

myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener()
public void onClick(DialogInterface arg0, int arg1)
Utility.pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Utility.pictureActionIntent, Utility.CAMERA_PICTURE);


After Selection of Image

– Yeah, Now you have select any single image and that will come with onActivityResult.
– Now do some copy & decoding task

The selection of image you will retun on the main activity with bitmap image
protected void onActivityResult(int requestCode, int resultCode, Intent data)
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Utility.GALLERY_PICTURE)
// data contains result
// Do some task
} else if (requestCode == Utility.CAMERA_PICTURE)
// Do some task

Copy, Decoding & Bitmap Creation Task

public void Image_Selecting_Task(Intent data) {
    try {
        Utility.uri = data.getData();
        if (Utility.uri != null) {
            // User had pick an image.
            Cursor cursor = getContentResolver().query(Utility.uri, new String[] {
            }, null, null, null);
            // Link to the image
            final String imageFilePath = cursor.getString(0);

            //Assign string path to File
            Utility.Default_DIR = new File(imageFilePath);

            // Create new dir MY_IMAGES_DIR if not created and copy image into that dir and store that image path in valid_photo

            // Copy your image 
            Utility.copyFile(Utility.Default_DIR, Utility.MY_IMG_DIR);

            // Get new image path and decode it
            Bitmap b = Utility.decodeFile(Utility.Paste_Target_Location);

            // use new copied path and use anywhere 
            String valid_photo = Utility.Paste_Target_Location.toString();
            b = Bitmap.createScaledBitmap(b, 150, 150, true);

            //set your selected image in image view

        } else {
            Toast toast = Toast.makeText(this, "Sorry!!! You haven't selecet any image.", Toast.LENGTH_LONG);
    } catch (Exception e) {
        // you get this when you will not select any single image 
        Log.e("onActivityResult", "" + e);


Create Directory if not Exist

// Create New Dir (folder) if not exist 
public static File Create_MY_IMAGES_DIR() {
    try {
        // Get SD Card path & your folder name
        MY_IMG_DIR = new File(Environment.getExternalStorageDirectory(), "/My_Image/");

        // check if exist 
        if (!MY_IMG_DIR.exists()) {
            // Create New folder 
            Log.i("path", ">>.." + MY_IMG_DIR);
    } catch (Exception e) {
        // TODO: handle exception
        Log.e("Create_MY_IMAGES_DIR", "" + e);
    return MY_IMG_DIR;

Copy Image at specific Directory in sdcard

// Copy your image into specific folder 
public static File copyFile(File current_location, File destination_location) {
    Copy_sourceLocation = new File("" + current_location);
    Paste_Target_Location = new File("" + destination_location + "/" + Utility.Get_Random_File_Name() + ".jpg");

    Log.v("Purchase-File", "sourceLocation: " + Copy_sourceLocation);
    Log.v("Purchase-File", "targetLocation: " + Paste_Target_Location);
    try {
        // 1 = move the file, 2 = copy the file
        int actionChoice = 2;
        // moving the file to another directory
        if (actionChoice == 1) {
            if (Copy_sourceLocation.renameTo(Paste_Target_Location)) {
                Log.i("Purchase-File", "Move file successful.");
            } else {
                Log.i("Purchase-File", "Move file failed.");

        // we will copy the file
        else {
            // make sure the target file exists
            if (Copy_sourceLocation.exists()) {

                InputStream in = new FileInputStream(Copy_sourceLocation);
                OutputStream out = new FileOutputStream(Paste_Target_Location);

                // Copy the bits from instream to outstream
                byte[] buf = new byte[1024];
                int len;

                while ((len = in .read(buf)) > 0) {
                    out.write(buf, 0, len);
                } in .close();

                Log.i("copyFile", "Copy file successful.");

            } else {
                Log.i("copyFile", "Copy file failed. Source file missing.");

    } catch (NullPointerException e) {
        Log.i("copyFile", "" + e);

    } catch (Exception e) {
        Log.i("copyFile", "" + e);
    return Paste_Target_Location;

11 thoughts on “Picture Selection from Camera & Gallery

  1. Nice tutorial..but when i take portrait mode pic from camera and click on save button..pic automatically rotated..can you help?


  2. the code is working good but in case of camera it showing the toast ..”you haven’t selected any image” after capturing.

    please reply soon


    1. Hello Gulshan, Yes because of in some of the device we are getting null response after selected image and that will throw us NullPointerExecption. We can handle that thing using onSaveInstanceState & onRestoreInstanceState.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s