Capture Image From Camera and Select Image From Gallery of Android Phone Using Android Studio

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.   
  24. public class MainActivity extends Activity {  
  25.     ImageView viewImage;  
  26.     Button b;  
  27.     @Override  
  28.     protected void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         setContentView(R.layout.activity_main);  
  31.         b=(Button)findViewById(R.id.btnSelectPhoto);  
  32.         viewImage=(ImageView)findViewById(R.id.viewImage);  
  33.         b.setOnClickListener(new View.OnClickListener() {  
  34.             @Override  
  35.             public void onClick(View v) {  
  36.                 selectImage();  
  37.             }  
  38.         });  
  39.     }  
  40.     @Override  
  41.     public boolean onCreateOptionsMenu(Menu menu) {  
  42.         // Inflate the menu; this adds options to the action bar if it is present.  
  43.         getMenuInflater().inflate(R.menu.main, menu);  
  44.         return true;  
  45.     }  
  46.       private void selectImage() {  
  47.         final CharSequence[] options = { "Take Photo""Choose from Gallery","Cancel" };  
  48.         AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);  
  49.         builder.setTitle("Add Photo!");  
  50.         builder.setItems(options, new DialogInterface.OnClickListener() {  
  51.             @Override  
  52.             public void onClick(DialogInterface dialog, int item) {  
  53.                 if (options[item].equals("Take Photo"))  
  54.                 {  
  55.                     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
  56.                     File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");  
  57.                     intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));  
  58.                     startActivityForResult(intent, 1);  
  59.                 }  
  60.                 else if (options[item].equals("Choose from Gallery"))  
  61.                 {  
  62.                     Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
  63.                     startActivityForResult(intent, 2);  
  64.                 }  
  65.                 else if (options[item].equals("Cancel")) {  
  66.                     dialog.dismiss();  
  67.                 }  
  68.             }  
  69.         });  
  70.         builder.show();  
  71.     }  
  72.     @Override  
  73.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  74.         super.onActivityResult(requestCode, resultCode, data);  
  75.         if (resultCode == RESULT_OK) {  
  76.             if (requestCode == 1) {  
  77.                 File f = new File(Environment.getExternalStorageDirectory().toString());  
  78.                 for (File temp : f.listFiles()) {  
  79.                     if (temp.getName().equals("temp.jpg")) {  
  80.                         f = temp;  
  81.                         break;  
  82.                     }  
  83.                 }  
  84.                 try {  
  85.                     Bitmap bitmap;  
  86.                     BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();  
  87.                     bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),  
  88.                             bitmapOptions);   
  89.                     viewImage.setImageBitmap(bitmap);  
  90.                     String path = android.os.Environment  
  91.                             .getExternalStorageDirectory()  
  92.                             + File.separator  
  93.                             + "Phoenix" + File.separator + "default";  
  94.                     f.delete();  
  95.                     OutputStream outFile = null;  
  96.                     File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");  
  97.                     try {  
  98.                         outFile = new FileOutputStream(file);  
  99.                         bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);  
  100.                         outFile.flush();  
  101.                         outFile.close();  
  102.                     } catch (FileNotFoundException e) {  
  103.                         e.printStackTrace();  
  104.                     } catch (IOException e) {  
  105.                         e.printStackTrace();  
  106.                     } catch (Exception e) {  
  107.                         e.printStackTrace();  
  108.                     }  
  109.                 } catch (Exception e) {  
  110.                     e.printStackTrace();  
  111.                 }  
  112.             } else if (requestCode == 2) {  
  113.                 Uri selectedImage = data.getData();  
  114.                 String[] filePath = { MediaStore.Images.Media.DATA };  
  115.                 Cursor c = getContentResolver().query(selectedImage,filePath, nullnullnull);  
  116.                 c.moveToFirst();  
  117.                 int columnIndex = c.getColumnIndex(filePath[0]);  
  118.                 String picturePath = c.getString(columnIndex);  
  119.                 c.close();  
  120.                 Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));  
  121.                 Log.w("path of image from gallery......******************.........", picturePath+"");  
  122.                 viewImage.setImageBitmap(thumbnail);  
  123.             }  
  124.         }  
  125.     }  
  126. }  
 
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 :)


Similar Articles