Taking a Picture with Camera (using built-in intent)

person Jason Huangfolder_openAndroid, Code, Javalocal_offer, , , access_time November 29, 2010

This example shows you easiest way to instruct Android to run Camera app (comes with android system) to take a photo and returns.

import needed for this to work:

import java.io.File;
 
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;


private constants & variable uses in the class:

	private static int TAKE_PICTURE = 1;
	private Uri outputFileUri;



This code shows how to call built-in camera intent in android:
this calls the Camera app to set the output file to save the camera image to this file name.

Once the code is run, the Android camera pops up, just take your photo, and click on “Done” button on the screen. That would close the camera app and returns to your own App.

	private void TakePhoto() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
 
		outputFileUri = Uri.fromFile(file);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
		startActivityForResult(intent, TAKE_PICTURE);
 
	}


You need to override the onActivityResult to handle when the camera returns to your app:

The following code simply display outputfilename as a string message. You can do whatever you need given the file name.

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
 
		if (requestCode == TAKE_PICTURE){
			ShowMessage(outputFileUri.toString());
		}
 
	}

Comments

  1. Very Helpful, much appreciated

  2. Hi, is very helpful. but got the problem, the image result is two picture. one picture in dcim and another in outside sdcard, what is the problem?

  3. Its nice. but how can i have a new image button to take pictures contiuesly without exiting the camera.

  4. 10-04 00:25:47.910: E/AndroidRuntime(11701): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity java.lang.NullPointerException

    it gives NPE

  5. Very brief and works like a charm!Thank u very much.Saved my life

  6. Nidheesh Vijay

    Your code was extremely helpful. I was able to sort out many issues in my code. But what if I want to store the captured image in a predefined directory. All the photos taken using this app goes to DCIM/Camera folder in my sdcard. I want it in a different directory. Can u please help me out?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>