Android – Take picture by using native camera

By -

Problem: Launch native camera application to capture image and use it inside imageview

Description:

I hope you may across the application in which they are launching camera to capture image and then
they use the captured image to show inside the imageview. So here is an article for you to
implement the Camera functionality to capture photo and then place the captured photo inside
the imageview.

Prerequisites to read this article:
1.android.provider.MediaStore.ACTION_IMAGE_CAPTURE
By using this intent, we can launch the camera and can capture the photo/snap.

2.startActivityForResult
Usually we start activity by using startActivity method, but here we will start the activity
by using startActivityResult method as we require result as captured image. In short, this will launch an Activity that provides a result, and then pass that result back to the Activity that launched it.

Note: It is not required to have the android.permission.CAMERA permission in the AndroidManifest.xml file as we are not accessing the CAMERA directly, but we are just launching the in-built camera application through the above mentioed intent (i.e. android.provider.MediaStore.ACTION_IMAGE_CAPTURE).

We can also speak about this question as “How to capture image using Camera and use it inside the android application?”.

Well, here is the Activity code and xml layout files, just create them and run your application.

CameraActivity.java


package com.paresh.cameracapturedemo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */

	Button btnTakePhoto;
	ImageView imgTakenPhoto;
	private static final int CAM_REQUREST = 1313;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnTakePhoto = (Button) findViewById(R.id.button1);
        imgTakenPhoto = (ImageView) findViewById(R.id.imageView1);

        btnTakePhoto.setOnClickListener(new btnTakePhotoClicker());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	// TODO Auto-generated method stub
    	super.onActivityResult(requestCode, resultCode, data);

    	  if (requestCode == CAMERA_PIC_REQUEST) {
    		  Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    		  imgTakenPhoto.setImageBitmap(thumbnail);
          }
    }

    class btnTakePhotoClicker implements Button.OnClickListener
    {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
		}
    }
}

————————————————————————————-
main.xml
————————————————————————————-

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

	<TextView
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Press the button, capture photo and enjoy!!"
	    android:id="@+id/textview1"/>

	<Button
		android:text="Take Photo!"
		android:id="@+id/button1"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_below="@+id/textview1">
	</Button>

	<ImageView
		android:id="@+id/imageView1"
		android:layout_height="match_parent"
		android:layout_width="match_parent"
		android:src="@drawable/icon"
		android:scaleType="centerCrop"
		android:layout_below="@+id/button1">
	</ImageView>
</RelativeLayout>

Paresh Mayani

Paresh Mayani is a lead android developer from India. Currently, He is Sr. Software engineer at InfoStretch Solutions Pvt. Ltd. He has been developing android apps since very 1st version i.e. Android 1.5, he says he has seen days and nights of Android history. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

  • http://in.linkedin.com/in/vikaskanani Vikas

    This is great, are you able to get exif information? I think it may not be possible, any way what resolution you can get? Do let us know, if you do more work on this. I can help me, in my apps. Right now I am working on BlackBerry App, once I finish, I can also participate to this work.

    Great work. Nice theme

    • http://technotalkative.wordpress.com Paresh N Mayani

      Hi vikas,

      Thanx for your reply and regarding captured image, i am directly placing the captured image inside the 300dip*300dip imageview.

  • bharat

    Is it possible to take screen shot of home screen(main screen), I ve tried and got success to take screen shot of current view .. but wat i want is i want to run service for take picture of view.. like screen capture use for windows o/s which takes screen shot after some intervals ..

    • http://technotalkative.wordpress.com Paresh N Mayani

      Hi bharat,

      I didnt get what you want to say exactly. It would be a great if you found more stuffs and solution on this post. Share if you know more.
      Thanx

  • Chandrabhushan

    Hi,

    Thanks for above information.

    I want to know one more thing. How to get the image location that is captured by Camera.

    I tried many things but still not working.

    Thanks in advance.

    • Chandrabhushan

      Hi,

      I managed to find some different solution.
      This can be done by giving our own file name to the captured image.

      But now i’m having another problem.
      After capturing the image we have save or discard option.
      I need to avoid it.

      Thanks in Advance.

  • Vijay

    your code is not working for me.it give me null pointer exception in onActivityResult at line Bitmap thumbnail = (Bitmap) data.getExtras().get(“data”);

    so please provide me solution asap…..

    Thanks in advance.

    • http://technotalkative.wordpress.com Paresh N Mayani

      Hello vijay, I have already tested this above code in samsung galaxy 3, galaxy S and galaxy tab as well. Its working fine in all these. Still let me check for the possible exception.

      • Vijay

        thanks for your quick reply. i am using LG Optimus Me LG P350. Is there a device specific problem ?

  • Sukjin Lee

    Thanks.
    but your code is not working for motolora zoom ( android 3.0 honeycomb ).
    the imageview is empty.
    any other example for honeycomb?

    • http://pareshnmayani.wordpress.com Paresh N Mayani

      I think there may be a device specific problem because i have already tested the same on HTC and Samsung branded android device(as you can also see the same in snap).

      Still i will check it out and tested the same on other branded android mobile device. In between, if you found any solution then please feel free to share with me and here.

  • Mukesh

    Hi,
    I’m using this code in my app along with this i’m trying to do some addition operation, i have to upload the captured image to server and also no need of saving the captured image in sdcard, can u suggest some ideas to do this,Plz….

    • http://pareshnmayani.wordpress.com Paresh N Mayani

      Hi mukesh,

      Based on the image uploading which i had done in past, i would suggest to convert the captured image into Base64 string and then upload this string to server. In short you need to apply Base64 encoding/decoding functionality.

  • Mukesh

    Thank u very much for your response paresh, i’ll try using Base64 and get back to you…:)

    • http://pareshnmayani.wordpress.com Paresh N Mayani

      Ok sure mukesh, Best luck for the implementation.

  • Vera

    Hey thanks for this tutorial <3 ..really helped !!!

  • Kumar

    Hi,

    I am using Cam application with my project when invoke the camera iam trying to press the Device back button
    without taking image or photo.it shows the error msg like your application stopped unexpectedly please try again how can i solve this..please give sample code.

    • http://www.technotalkative.com/ Paresh N. Mayani

      Yes it gives error because it return nothing i.e. null.

      So you have to putt a condition inside onActivityResult() method.

      if(data!=null)
      {
      if (requestCode == CAMERA_PIC_REQUEST) {
      Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
      imgTakenPhoto.setImageBitmap(thumbnail);
      }
      }

  • Ravirajcm

    put that code here plz

  • Android Amitsuri

    Nice Tutorial…….

    Please help i want an app in which user will capture an image and at same time can send that image to Web or Remote Server or Upload to Facebook????

  • lenaoquica

    thnks man!

  • Nihar

    Hi Paresh ,I am a new comer to android,
    i followed the code executed but for some reason i can not see the stored image in gallery …(not sure even the image is getting saved or not)
    can u help regarding that
    thanks in advance

    • http://www.technotalkative.com/ Paresh Mayani

      When you create a photo through an intent, you should know where your image is located, because you said where to save it in the first place.

      The following example method demonstrates how to invoke the system’s media scanner to add your photo to the Media Provider’s database, making it available in the Android Gallery application and to other apps.


      private void galleryAddPic() {
      Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
      File f = new File(mCurrentPhotoPath);
      Uri contentUri = Uri.fromFile(f);
      mediaScanIntent.setData(contentUri);
      this.sendBroadcast(mediaScanIntent);
      }