Introduction

This article explains how to open the gallery in your phone and display the selected images, capture a photo from the camera and save it to the gallery of your Android phone.
First, the user will need to choose if he/she wants to select an image from the gallery or wants to capture an image from the camera. Then depending on the option chosen by the user, we will either open the gallery or capture an image.
Step 1
Open "AndroidManifest" and add the following code to it:
  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  2. package="com.chhavi.uploadingandviewimage"
  3. android:versionCode="1"
  4. android:versionName="1.0" >
  5. <uses-permission android:name="android.permission.CAMERA" />
  6. <uses-feature android:name="android.hardware.camera" />
  7. <uses-feature android:name="android.hardware.camera.autofocus" />
  8. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  9. <uses-sdk
  10. android:minSdkVersion="7"
  11. android:targetSdkVersion="16" />
  12. <application
  13. android:allowBackup="true"
  14. android:icon="@drawable/ic_launcher"
  15. android:label="@string/app_name"
  16. android:theme="@style/AppTheme" >
  17. <activity
  18. android:name="com.chhavi.uploadingandviewimage.MainActivity"
  19. android:label="@string/app_name" >
  20. <intent-filter>
  21. <action android:name="android.intent.action.MAIN" />
  22. <category android:name="android.intent.category.LAUNCHER" />
  23. </intent-filter>
  24. </activity>
  25. </application>
  26. </manifest>
Note the permission "WRITE_EXTERNAL_STORAGE" is to save the image captured to the gallery. "CAMERA" permissions enables use of the camera of your Android phone.
Step 2
Open "activity_main" and add the following code to it:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:id="@+id/LinearLayout1"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:orientation="vertical"
  7. android:padding="10dp" >
  8. <LinearLayout
  9. android:layout_width="match_parent"
  10. android:layout_height="wrap_content"
  11. android:gravity="center"
  12. android:padding="5dp" >
  13. <Button
  14. android:id="@+id/btnSelectPhoto"
  15. android:layout_width="match_parent"
  16. android:layout_height="wrap_content"
  17. android:text="Select Photo" />
  18. </LinearLayout>
  19. <LinearLayout
  20. android:layout_width="match_parent"
  21. android:layout_height="match_parent"
  22. android:orientation="vertical"
  23. android:padding="10dp" >
  24. <ImageView
  25. android:id="@+id/viewImage"
  26. android:layout_width="match_parent"
  27. android:layout_height="wrap_content"
  28. android:src="@drawable/camera" />
  29. </LinearLayout>
  30. </LinearLayout>
The layout looks like:
im1.jpg
Later the selected image will be displayed in the ImageView.
Step 3
Open "MainActivity" and add the following code to it:
  1. package com.chhavi.uploadingandviewimage;
  2. import android.app.AlertDialog;
  3. import android.content.DialogInterface;
  4. import android.content.Intent;
  5. import android.database.Cursor;
  6. import android.graphics.Bitmap;
  7. import android.graphics.BitmapFactory;
  8. import android.net.Uri;
  9. import android.os.Bundle;
  10. import android.app.Activity;
  11. import android.os.Environment;
  12. import android.provider.MediaStore;
  13. import android.util.Log;
  14. import android.view.Menu;
  15. import android.view.View;
  16. import android.widget.Button;
  17. import android.widget.ImageView;
  18. import java.io.File;
  19. import java.io.FileNotFoundException;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. import java.io.OutputStream;
  23. public class MainActivity extends Activity {
  24. ImageView viewImage;
  25. Button b;
  26. @Override
  27. protected void onCreate(Bundle savedInstanceState) {
  28. super.onCreate(savedInstanceState);
  29. setContentView(R.layout.activity_main);
  30. b=(Button)findViewById(R.id.btnSelectPhoto);
  31. viewImage=(ImageView)findViewById(R.id.viewImage);
  32. b.setOnClickListener(new View.OnClickListener() {
  33. @Override
  34. public void onClick(View v) {
  35. selectImage();
  36. }
  37. });
  38. }
  39. @Override
  40. public boolean onCreateOptionsMenu(Menu menu) {
  41. // Inflate the menu; this adds options to the action bar if it is present.
  42. getMenuInflater().inflate(R.menu.main, menu);
  43. return true;
  44. }
  45. private void selectImage() {
  46. final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
  47. AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
  48. builder.setTitle("Add Photo!");
  49. builder.setItems(options, new DialogInterface.OnClickListener() {
  50. @Override
  51. public void onClick(DialogInterface dialog, int item) {
  52. if (options[item].equals("Take Photo"))
  53. {
  54. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  55. File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
  56. intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
  57. startActivityForResult(intent, 1);
  58. }
  59. else if (options[item].equals("Choose from Gallery"))
  60. {
  61. Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  62. startActivityForResult(intent, 2);
  63. }
  64. else if (options[item].equals("Cancel")) {
  65. dialog.dismiss();
  66. }
  67. }
  68. });
  69. builder.show();
  70. }
  71. @Override
  72. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  73. super.onActivityResult(requestCode, resultCode, data);
  74. if (resultCode == RESULT_OK) {
  75. if (requestCode == 1) {
  76. File f = new File(Environment.getExternalStorageDirectory().toString());
  77. for (File temp : f.listFiles()) {
  78. if (temp.getName().equals("temp.jpg")) {
  79. f = temp;
  80. break;
  81. }
  82. }
  83. try {
  84. Bitmap bitmap;
  85. BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
  86. bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
  87. bitmapOptions);
  88. viewImage.setImageBitmap(bitmap);
  89. String path = android.os.Environment
  90. .getExternalStorageDirectory()
  91. + File.separator
  92. + "Phoenix" + File.separator + "default";
  93. f.delete();
  94. OutputStream outFile = null;
  95. File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
  96. try {
  97. outFile = new FileOutputStream(file);
  98. bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
  99. outFile.flush();
  100. outFile.close();
  101. } catch (FileNotFoundException e) {
  102. e.printStackTrace();
  103. } catch (IOException e) {
  104. e.printStackTrace();
  105. } catch (Exception e) {
  106. e.printStackTrace();
  107. }
  108. } catch (Exception e) {
  109. e.printStackTrace();
  110. }
  111. } else if (requestCode == 2) {
  112. Uri selectedImage = data.getData();
  113. String[] filePath = { MediaStore.Images.Media.DATA };
  114. Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
  115. c.moveToFirst();
  116. int columnIndex = c.getColumnIndex(filePath[0]);
  117. String picturePath = c.getString(columnIndex);
  118. c.close();
  119. Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
  120. Log.w("path of image from gallery......******************.........", picturePath+"");
  121. viewImage.setImageBitmap(thumbnail);
  122. }
  123. }
  124. }
  125. }
In the code above, "AlertDialog" will create a pop-up dialog box that will ask the user to choose "Take Photo", in other words capture an image from the camera or "Choose from Gallery" or "Cancel". Note that in both "Choose from Gallery" and "Take Photo", you can add any code in "startActivityForResult".
Output snapshots
Run the application on an Android phone.
The first screen looks like,
im2f.png
Clicking on the button "Select Photo" you will get the alert dialog box-like,
im3f.png
Selecting "Take photo" will open your camera.
im4f.png
After clicking the photo, you can discard it or save it by selecting the tick mark:
im5f.png
Finally, the image clicked will be displayed in the ImageView.
im8f.png
Selecting "Choose from Gallery" will open your gallery (note that the image captured earlier has been added to the phone gallery).
im6f.jpg
Selecting an image from these albums will be displayed in the ImageView like:
im7f.png

Summary

In this article, we learned about Capture Image From Camera and Select Image From Gallery of Android Phone Using Android Studio.
Thank you... Enjoy coding :)