Now a days lot of apps offer users to take pictures and record videos for various kind of purposes. This tutorial describes how to do the same in your applications.

Integrating camera can be done in two ways. One is to use android inbuilt camera app which is very easy process. This method won’t give you much control over camera as everything is taken care by inbuilt camera app. This way will be appropriate when your app need just a picture or video from camera.

Second way is to build a custom camera interface and adding the functionality. This needs higher effort as we have to do everything by our own. Building custom camera interface will be useful when you are building an app which mainly deals with images and videos like Instagram.

This tutorial covers the first scenario which is using android in build camera app in your application.

android working with camera api

Let’s start by creating a new project

1. Create a new project in Eclipse from File ⇒ New ⇒ Android ⇒ Application Project and fill all the required information. I left my main activity as MainActivity.java

Adding Permissions / Features

2. Working with camera needs set of permissions and features in the AndroidManifest.xml file. Add following in your AndroidManifest.xml

android.hardware.camera – Required to use camera hardware
WRITE_EXTERNAL_STORAGE – Required to store images / video in external storage
RECORD_AUDIO – Needed when recording video with audio

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.androidcameraapi"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <!-- Accessing camera hardware -->
    <uses-feature android:name="android.hardware.camera" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="info.androidhive.androidcameraapi.MainActivity"
            android:label="@string/app_name"
            android:configChanges="orientation|keyboard|keyboardHidden"
            android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3. For demo purpose I have created a simple layout with two Buttons, ImageView and VideoView. Open your layout file of your main activity activity_main.xml and paste the following code.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:baselineAligned="false"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical" >

        <!-- Capture picture button -->
        <Button
            android:id="@+id/btnCapturePicture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Take a Picture"
            android:layout_marginBottom="10dp"/>

        <!-- Record video button -->
        <Button
            android:id="@+id/btnRecordVideo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Record a Video" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Preview" 
            android:padding="10dp"
            android:textSize="15dp"/>

        <!-- To display picture taken -->
        <ImageView
            android:id="@+id/imgPreview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone" />

        <!-- To preview video recorded -->
        <VideoView
            android:id="@+id/videoPreview"
            android:layout_width="wrap_content"
            android:layout_height="400dp"
            android:visibility="gone" />
    </LinearLayout>

</LinearLayout>

4. In MainActivity.java I started with adding code like declaring required variables, referencing the xml UI elements and adding button click listeners.

I kept default location to store images and videos in “Hello Camera” directory which will be created under SD card Pictures/Hello Camera

public class MainActivity extends Activity {

	// Activity request codes
	private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
	private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;

	// directory name to store captured images and videos
	private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";

	private Uri fileUri; // file url to store image/video

	private ImageView imgPreview;
	private VideoView videoPreview;
	private Button btnCapturePicture, btnRecordVideo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		imgPreview = (ImageView) findViewById(R.id.imgPreview);
		videoPreview = (VideoView) findViewById(R.id.videoPreview);
		btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
		btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);

		/**
		 * Capture image button click event
		 * */
		btnCapturePicture.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// capture picture
				captureImage();
			}
		});

		/**
		 * Record video button click event
		 */
		btnRecordVideo.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// record video
				recordVideo();
			}
		});
	}
}

Checking Camera Availability

5. You might think about the scenario if the device does’t have the camera. So before using any camera feature, it is better to check availability of the camera. This can be done in two ways

a. Defining the camera feature in AndroidManifest.xml

By adding android.hardware.camera feature in manifest file, Google Play prevents the app to be installed on devices those doesn’t have camera.

b. Checking in code manually
You can also do a check in the code.

/**
	 * Checking device has camera hardware or not
	 * */
	private boolean isDeviceSupportCamera() {
		if (getApplicationContext().getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_CAMERA)) {
			// this device has a camera
			return true;
		} else {
			// no camera on this device
			return false;
		}
	}

Taking a Picture

6. As we are using android’s inbuilt camera app, launching the camera and taking the picture can done with very few lines of code using the power of Intent.

MediaStore.ACTION_IMAGE_CAPTURE – Requesting camera app to capture image
MediaStore.EXTRA_OUTPUT – Specifying a path where the image has to be stored

captureImage() function will launch the camera to snap a picture.

	 /*
	 * Capturing Camera Image will lauch camera app requrest image capture
	 */
	private void captureImage() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

		intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

		// start the image capture Intent
		startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
	}

7. As we are starting an activity using startActivityForResult(), we can expect some result in onActivityResult() method. Override this method in your activity like below. We also can check whether the user successfully took the picture or cancelled the camera.

	/**
	 * Receiving activity result method will be called after closing the camera
	 * */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// if the result is capturing Image
		if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				// successfully captured the image
				// display it in image view
				previewCapturedImage();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled Image capture
				Toast.makeText(getApplicationContext(),
						"User cancelled image capture", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to capture image
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}
android launching camera application

Displaying Captured Image

As we used inbuilt camera app to capture the picture we won’t get the image in onActivityResult() method. In this case data parameter will be always null. We have to use fileUri to get the file path and display the image

8. onActivityResult() we use CAMERA_CAPTURE_IMAGE_REQUEST_CODE to check whether response came from Image Capture activity or Video Capture acivity. Call previewCapturedImage() in onActivityResult after doing this check.

/*
	 * Display image from a path to ImageView
	 */
	private void previewCapturedImage() {
		try {
			// hide video preview
			videoPreview.setVisibility(View.GONE);

			imgPreview.setVisibility(View.VISIBLE);

			// bimatp factory
			BitmapFactory.Options options = new BitmapFactory.Options();

			// downsizing image as it throws OutOfMemory Exception for larger
			// images
			options.inSampleSize = 8;

			final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
					options);

			imgPreview.setImageBitmap(bitmap);
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}
android camera taking a picture

Recording a Video

9. Launching camera to record video is same as capturing image. But instead of MediaStore.ACTION_IMAGE_CAPTURE we use MediaStore.ACTION_VIDEO_CAPTURE.

Here we also define video quality using MediaStore.EXTRA_VIDEO_QUALITY flag. Keeping this value as 1 records video at high quality with higher file size and keeping 0 records the video at lower quality and lower file size.

Call following function on record video button click event

	 /*
	 * Recording video
	 */
	private void recordVideo() {
		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

		fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

		// set video quality
		// 1- for high quality video
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

		intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

		// start the video capture Intent
		startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
	}

And in onActivityResult() method check the success of recording.

/**
	 * Receiving activity result method will be called after closing the camera
	 * */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// if the result is capturing Image
		if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
			// code to check capture image response
		} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				// video successfully recorded
				// preview the recorded video
				previewVideo();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled recording
				Toast.makeText(getApplicationContext(),
						"User cancelled video recording", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to record video
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to record video", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}

Previewing Recorded Video

10. Following function will play recorded video in VideoView. Call this method in onActivityResult method after checking RESULT_OK for camera response

/*
	 * Previewing recorded video
	 */
	private void previewVideo() {
		try {
			// hide image preview
			imgPreview.setVisibility(View.GONE);

			videoPreview.setVisibility(View.VISIBLE);
			videoPreview.setVideoPath(fileUri.getPath());
			// start playing
			videoPreview.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

Avoiding NullPointerException after taking camera picture

11. It is known issue that everybody faces a NullPointerException while working with inbuilt camera application. When we launch the camera it actually restarts our activity which causes fileUri to be null. So when we use fileUri to display captured image or recorded video, we will get NullPointerException.

So in order to fix it we have to use onSaveInstanceState() and onRestoreInstanceState() to retain fileUri value. Add following code in MainActivity.java

	/**
	 * Here we store the file url as it will be null after returning from camera
	 * app
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		// save file url in bundle as it will be null on scren orientation
		// changes
		outState.putParcelable("file_uri", fileUri);
	}

	/*
	 * Here we restore the fileUri again
	 */
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);

		// get the file url
		fileUri = savedInstanceState.getParcelable("file_uri");
	}

Helper Methods

12. Add following methods in your main activity class. These methods helps in creating and getting files from SD card.

	 /**
	 * Creating file uri to store image/video
	 */
	public Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/*
	 * returning image / video
	 */
	private static File getOutputMediaFile(int type) {

		// External sdcard location
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				IMAGE_DIRECTORY_NAME);

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
						+ IMAGE_DIRECTORY_NAME + " directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
		} else if (type == MEDIA_TYPE_VIDEO) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "VID_" + timeStamp + ".mp4");
		} else {
			return null;
		}

		return mediaFile;
	}

It is advisable to use a real device and test the application.

Final Code

Here is the complete code of MainActivity.java

package info.androidhive.androidcameraapi;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;

public class MainActivity extends Activity {

	// Activity request codes
	private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
	private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;

	// directory name to store captured images and videos
	private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";

	private Uri fileUri; // file url to store image/video

	private ImageView imgPreview;
	private VideoView videoPreview;
	private Button btnCapturePicture, btnRecordVideo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		imgPreview = (ImageView) findViewById(R.id.imgPreview);
		videoPreview = (VideoView) findViewById(R.id.videoPreview);
		btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
		btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);

		/**
		 * Capture image button click event
		 */
		btnCapturePicture.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// capture picture
				captureImage();
			}
		});

		/**
		 * Record video button click event
		 */
		btnRecordVideo.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// record video
				recordVideo();
			}
		});

		// Checking camera availability
		if (!isDeviceSupportCamera()) {
			Toast.makeText(getApplicationContext(),
					"Sorry! Your device doesn't support camera",
					Toast.LENGTH_LONG).show();
			// will close the app if the device does't have camera
			finish();
		}
	}

	/**
	 * Checking device has camera hardware or not
	 * */
	private boolean isDeviceSupportCamera() {
		if (getApplicationContext().getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_CAMERA)) {
			// this device has a camera
			return true;
		} else {
			// no camera on this device
			return false;
		}
	}

	/**
	 * Capturing Camera Image will lauch camera app requrest image capture
	 */
	private void captureImage() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

		intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

		// start the image capture Intent
		startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
	}

	/**
	 * Here we store the file url as it will be null after returning from camera
	 * app
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		// save file url in bundle as it will be null on scren orientation
		// changes
		outState.putParcelable("file_uri", fileUri);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);

		// get the file url
		fileUri = savedInstanceState.getParcelable("file_uri");
	}

	/**
	 * Recording video
	 */
	private void recordVideo() {
		Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

		fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

		// set video quality
		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

		intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
															// name

		// start the video capture Intent
		startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
	}

	/**
	 * Receiving activity result method will be called after closing the camera
	 * */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// if the result is capturing Image
		if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				// successfully captured the image
				// display it in image view
				previewCapturedImage();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled Image capture
				Toast.makeText(getApplicationContext(),
						"User cancelled image capture", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to capture image
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
						.show();
			}
		} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				// video successfully recorded
				// preview the recorded video
				previewVideo();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled recording
				Toast.makeText(getApplicationContext(),
						"User cancelled video recording", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to record video
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to record video", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}

	/**
	 * Display image from a path to ImageView
	 */
	private void previewCapturedImage() {
		try {
			// hide video preview
			videoPreview.setVisibility(View.GONE);

			imgPreview.setVisibility(View.VISIBLE);

			// bimatp factory
			BitmapFactory.Options options = new BitmapFactory.Options();

			// downsizing image as it throws OutOfMemory Exception for larger
			// images
			options.inSampleSize = 8;

			final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
					options);

			imgPreview.setImageBitmap(bitmap);
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Previewing recorded video
	 */
	private void previewVideo() {
		try {
			// hide image preview
			imgPreview.setVisibility(View.GONE);

			videoPreview.setVisibility(View.VISIBLE);
			videoPreview.setVideoPath(fileUri.getPath());
			// start playing
			videoPreview.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * ------------ Helper Methods ---------------------- 
	 * */

	/**
	 * Creating file uri to store image/video
	 */
	public Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/**
	 * returning image / video
	 */
	private static File getOutputMediaFile(int type) {

		// External sdcard location
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				IMAGE_DIRECTORY_NAME);

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
						+ IMAGE_DIRECTORY_NAME + " directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
		} else if (type == MEDIA_TYPE_VIDEO) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "VID_" + timeStamp + ".mp4");
		} else {
			return null;
		}

		return mediaFile;
	}
}
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Sukumar

    Nice Example

  • Nice tutorial

  • Jeffy Lazar

    Thank you so much …thank you so much …..thanks a lot man …you are the best 🙂 🙂

  • Sagar Maiyad

    Sorry, but you are not using any Camera API.. its buitin camera..

    • I’ll change the title

      • Sagar Maiyad

        Okey, but can you tell me, is it working in all devices or not.??

  • Ajay Patel

    Your site now looks like songs.pk, its quality is not same as previous one. Like songs.pk your site full of adverts. It really sucks 🙁

    • I need some money to maintain site right ?

      • suncap

        I will click on all your adverts

        • Hi Suncap, Thanks for the help. But if we click ads intentionally my ads account will be cancelled 🙂

          • Connery Sean

            Hey I like your site !
            Keep up the good work

          • Jeffy Lazar

            ads are not of any problem …we dont even notice the ads as long as you keep posting such amazing and yet so easy to understand Android Tutorials.

            Keep up the great work 🙂 🙂

          • Krunal Doshi

            Start Premium Tutorial that only Premium users can access.

      • maulik

        we all are eagerly waiting for the Design and Tips section!

        • Yeah, they are under construction…

          • Steffy

            Sir do you use any cms ?

      • suncap

        AdsBlock+ FTW !!! 😛

  • Sagar Maiyad

    Have you any Example related to Camera API..?? if, then please publish here.. it will very useful for all and specialy for me.

  • Jumman

    How can I crop from camera preview with bounding box for selecting the region before capturing the images? like “Translanguage OCR” (https://play.google.com/store/apps/details?id=com.translanguage.free.version&hl=en) ,please help me regarding this .thanks

  • Lakshmi Reddy Kanneti

    sir you r mention fileurl in path.where is the image are video store.i want to store a capture images are videos in remote server.how can i do that. i am new for android .give me a start up .and also i am using that images and videos to send a message like whatapp.

    • Connery Sean

      My guess would be that you have to store your Images on your mobile first, and than push them online using some other technology to comunicate with your web server

      • Correct!

        • koko landry

          what are those technologies that I can use to get my picture on a remote server? i really need this for my project. can u please help?

  • Steffy

    Nice tutorial ! Sir do you use any CMS for this website ? Its awesome !

  • sakthivel

    thanks good tutorial. my small request make it android seekbar for value increment and decrement tutorial.
    best thanks
    sakthivel

    • sdfgh

      hhhhhh

  • Tulai Paul

    Such articles may prompt the mobile ad network companies and their apps and games developers to provide apps and games that are based on live camera. The list of such companies have been increasing constantly like admob, revmob, chartboost, tapjoy, adcolony, appnext, inmobi and so on

  • Joey

    Great tutorial man! Thnx! But do you know why my images show up with the default file names? The code renames video files, that’s good! Also, i can’t move the images to a custom folder? Hope you can help me!

  • mangesh kaduskar

    I took video from camera but now i want to upload it to YouTube. Will you please give me tutorial of how to upload video to YouTube.

  • Pablo

    Ravi I am getting an error:
    Pictures work just fine, but when I try to record video, the camera is launched but when I stop recording the app crashes, any ideas? I am running it on a 2.3.6 android version.

    • Shri Kant

      same problem here.

      • dhnjy 18

        Am also facing the same problem. did you find any solution. plz tell me

  • Douglas Roos

    How can i change the resolution and quality of the photo because when i send the photo to my webserver takes a long time, the photos have a size of 2mb or more.

    • Hari Haran Ayyappan

      Hi Roos , In what format you are sending the pics to server

      • Douglas Roos

        Hi Hari, i’m sending the photos in JPG format through MultiPartEntityBuilder, i’ve solved the problem downsampling the photo from the bitmap, rewriting the original photo and sending it to the server.

        • Hari Haran Ayyappan

          MultiPartEntity means are you using apache http multi entity jars? I am decompressing bitmap and sending .when i am decompressing , and subimtting to server i am getting out of memory exception. Did you experience this issue

  • Ugur Cakmak

    I’m triggering image capture intent from a custom dialogs button. After I succesfully saving the image to sdcard, application restarts and my dialog dissappears. I don’t want to restart my application, it’s not I want. I simply want after capture, return to where I was. How can I do that ?

    • Uğur Çakmak

      I commented out InstanceState Methods and now I’m fine. but in order to save my images in portrait mode, I should take a picture in landscape mode. I want to save images in proper modes like portrait in portrait, you know the rest. any suggestions ?

  • Gilbert

    Great tutorial man

  • jj

    this tutorial isn’t on the custom camera i found a better one here http://appskort.com/android-camera-tutorial

    • Ravi Kant chauhan

      brother can u send me complete code with directory structure for only camera activity..that means i want to take a pic and want to upload to the server..pls brother send me

      ravikantchauhan009@gmail.com

    • Carlos

      it doesn´t work in Tablet Nexus 7, because it has no SD card !!

      • Carlos

        Your app works amazing in my Nexus 7 – 2013 !!, thanks Ravi

  • Ankita Patel

    sir how to integrate this camera code in to all type of barcode reader in android

  • Stefan

    Whenever I start the app there is a black background until I click the button… Afterwards it’s working just fine… Does anyone know this problem?

  • Poojan Sharma

    Hi Ravi,
    I’m having some problem, i’ve implemented your code into my app but i’m confused as to how to store the captured image into my local storage. Please help me on this.

  • gautam behera

    Hello,
    I ran your code but I am not able to get a portrait image. When I take an image in portrait it becomes landscape in the app.
    So is it possible to get a portrait image.

    • Dhruvit Darji

      that is the bug which is already reported in android community and still they are working to fix it.. some people suggest to use EXIF techniques but be frank then it is not working in most of devices it always returning 0 rotation… if you have found any solution then plz let me know.. i badly require that…

  • Derdus

    Your code works perfectly well, but i am not able to capture the video capture. Help me please

  • Tyler

    Hello, my phone does not have a sd card(at least no sd card slot) so where would it be storing my pictures when I take them?

    Thank you,
    Tyler

  • Jekyll Bermeo

    Hello how will i fetch the captured image path?

  • koko landry

    nice tutorial. how do i upload pictures/videos to a remote server ? this will be of much help. tx

  • Andre Piper

    How do I set the recording limit, I didn’t see that in the code.

  • Kinjal Patel

    how we tak more than one shots programatically for android custom camera?

  • emiliano

    Hi, how can i adapt this code to use inside fragment? Thanks.-

    • Muaaz Odabashi

      any luck?

  • Mona Elgnedy

    Plz , If I want camera hidden and silent ?? how

  • Sinan

    How can I save the captured image on a server (localhost) instead of the sd-card?

    • Walter Reyes

      You would also need to make an api to handle the http calls. This is not too difficult with php and slim framework

      • Sinan

        Hi Walter,
        Thanks for your answer. But are you able to provide me some helpful links or tutorials ?

  • Gabriel Galang

    how could i save this on database sqlite???

    and anytutorial for camera to blob then to sqlite / sqlite to imageview 😀

    • golla priyanka

      hie if u got the answer please explain me

      • Why do you want to store the image in SQlite?

  • Paradisos

    Can please someone tell me what the “Activity request codes” is and why do I have to add a number ?
    I don’t see any use after….

    • may be since it is accessing camera API it may be response code like HTTP respnse
      i guessed answer with http response
      pls go through the Camera API in docs!

  • Carlos

    Excellent tutorial Ravi, congratulations. Please, let me do it a question. How could I add effect image to you camera?, for example color gray, sepia toning in Android NDK C++/C?.
    Regards,
    Carlos

  • Carla

    my videos and photos are not saved, do I have to adjust some code?

  • jason

    Hi thx for this great tuto. Plz how can we store the captured photo or video directly on mysql database and how can we resize the picture before storage !!!!

    • ubro

      Any answer Ravi plz for this question ???

    • Jasson Faerron

      i think you need to use Bitmap and create a byte[] from Bitmap and then create the statement to store

  • nice tutorial @ravi8x:disqus sir! easy to understand!

    • SIR NAME İS MAHO

      SİİİR.. SİİİR RAVİİİİ.. SİR.. IIIH .. IMMMM SIRR

  • Join Kelly

    Why not support nexus 7 device ?

  • Nagginda Sumayyia

    May anyone help me please. i want to know how to submit both the image and the video captured from android device to mysql/PHP database.

  • Huỳnh Thanh Tuấn

    someone help me…how to call intent into ArrayAdapter…i have one gridview and once gridview_item have a image…i want when click into this image,it will call intent give them take a picture

  • Laureen Tan

    Thank you for the tutorial. But anyone know how I can retrieve all the images that is saved in folder after following the steps above from my phone?

  • Absar Hussain

    i copy paste that code .. no errors .. But this code is not working.. can anyone help me??

  • youming2007

    There are some code errors in this tutorial: (It takes me 2 hours to get around with them xD)

    1. When recording video, it will throw error after recording and saving recorded video to the location specified in MediaStore.EXTRA_OUTPUT, as mentioned here: http://stackoverflow.com/questions/12458318/nullpointerexception-at-com-sec-android-app-camera-camcorderengine-renametempfil. Solution is just remove that line and assign a value to fileUri = data.getData() in onActivityResult callback. The recorded video would be save in default location.

    2. Use videoPreview.setVideoURI(fileUri) instead of videoPreview.setVideoPath(fileUri.getPath) when working with the above workaround because data.getData() return a uri related to a media content provider instead of actual path.

    Anyway, it’s an awesome tutorial.

    • sanjay

      Thanks, same error i was also getting while saving the video file.

  • ah_trini

    good tutorial :)!

    It will also threw errors for the overidden “SetOnClickListener”methods for the buttons.

    Remove those two methods and add these for the respective button tagsin xml.
    android:onClick=”captureImage”

    android:onClick=”recordVideo”

    • ah_trini

      oh and change the method signatures to:
      public void captureImage(View view){}
      public void recordVideo(View view){}

  • sania12

    it s working fine but it s taking such a long time after capturing image

  • Naman Gupta

    Hey! The preview is not working in the app. The Image gets stored in the right directory, but after the camera closes, their is nothing to display on the app activity.

  • Damian Dennis

    nice one, best tutorial so far.

  • yamuna

    i import your source code but my application displaying force to close message

  • yamuna

    when i click take the photo button it waits 2sec and displays force to close an application message

  • mukesh

    Hey! can we do same for front facing camera ?

  • Mukesh Krishnan

    Thank you coder !!!! you are really awesome ……..love you

  • meghana

    nice tut…

  • prasad Vdv

    can display camera in layout within the app

  • Atul

    can anyone tell the code that will directly start video recording on button click….bcoz above code calls system camera and then we press button for recording(ie.takes 2 clicks….i want it in a single click)

  • Guest

    This code has not work in android 4.4.4 kit kat

  • Toqeer

    can we add textview during video recording

  • Vikas Goyal

    this code is not working

  • Akash Saviaram

    great tutorial.. thank you so much.!

  • Amadeus Prime

    Hi Guys, what if i want to capture multiple photos and display them in a listView or recyclerView instead of an imageView, any suggestions?

  • Khyati

    i get null pointer exception in getOutputMediaFileUri()

  • great work !!

  • thomas kerioh

    i love this.thanks for the great work but one question,what changes do i need to make if am using android studio?

    • Satish Rajput

      You can simply import the project in Android Studio. Studio detects itself whether the project created in eclipse. If so then Studio tries to configure as suitable for Android Studio Project.
      It can take some time showing message…gradle is building…

      If it still not working for you then you need to do….
      create a new application in android studio then just copy and paste entire code from old project’s MainActivity to new Project’s MainActivity. Also copy permissions in new Manifest file.

  • Abhijit Murgod

    sir, can i capture image by double or single clicking on any part of camera (not the inbuilt camera button in android mobile phone), when camera is open in the mobile…
    I have created an App for blind people, that must capture image (which contains text), if text is present App will convert image to voice.. blind can hear the voice.. but the problrem is they cannot see the image capture button in phone… please help me by sending the code for this problem.. problem statement : “if blind people clicks on any part of camera, the application should capture image”. please do help

  • chha

    working code.. great job. thank you

  • Stark

    Thanks for your post.
    I found error in
    fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

    and MEDIA_TYPE_IMAGE too.
    I thought it is my real device don’t have external storage?

  • Saba Younis

    great work thanks

  • vishal singhal

    hello sir, i want to capture three images in one activity on clicking 3 camera icons and showing in three image views, but i want to upload these images on server but i got null in intent data in OnActivityResult. please help me

  • amutisya

    thanks a lot androidhive..

  • ANKITA

    we are getting MultiPartEntity deprecated
    What to do? Please help…its urgent

  • Gaurav Meghanathi

    how to store gallery images like 4 to 5mb in sqlite database.dynamic if any one can tell me…?

  • Sumeet Rathore

    what to do if i need to store capture image into specific folder not in gallery like i need to create folder and store that capture image. what changes i need to do in this same code. Anyone?

    • Sumeet Rathore

      @ravi8x:disqus sir can you please help me here?

  • Nidhin Kumar

    Hi i have used the above code and tried to capture image and it works fine but if i capture the image in some other devices like samsung the image gets rotated to 90 degrees for that what i have to do to avoid the rotation of images while capturing

  • Rajesh

    Nice and Working Code………Thank You…..

  • Venktesh Sakthi

    whats the value of RESULT_OK???

    • TimeTraveler

      if you are using Activity then its Activity.RESULT_OK ,if it is fragment then getactivity().RESULT_OK.

  • manivel.m

    great a working thanks

  • Bhanu Prakash

    what is the finish() method for?

    • chandan lal

      to exit from application.

  • Johnny

    This tutorial is great! I do want to ask: what would you need to change/add to make this work from a fragment?

    • varun

      i have same query

  • puntodamar

    the code is working. but I can’t find the pictures on my phone gallery.

  • TimeTraveler

    As always another great Tutorial from RAVI.. 🙂

  • md. saifuddin Khan

    hello ravi, I want to store the images in sequence naming like IMG_1,IMG_2… and so on.
    PLZ help me!!!

    • lowi adrian colinares

      File mediaFile;

      if (type == MEDIA_TYPE_IMAGE) {
      mediaFile = new File(mediaStorageDir.getPath() + File.separator
      + “IMG_” + 1 + “.jpg”);

      }

  • sanjay

    Hi Ravi, app crashes once you save the video and try to come back from camera activity. Can we close camera activity once we save the video file?

  • RiShi DeEp

    getOutputMediaFileUri(CameraActivity.java:249)
    captureImage(CameraActivity.java:110)
    access$000(CameraActivity.java:27)
    $1.onClick(CameraActivity.java:65)

    errors

  • Rahul

    how to manage image get rotate in android device

  • ancy

    how to get rectangle overlay on camera

  • Mr. Ben

    Hi Sir Ravi
    im Ben from Malaysia
    i need your help by your expert in android
    i cant solve that how to code an application by using android phone camera to scan the colors and display the colors name
    My project is want to help whose colors blindness people
    may i get your help ? or any advice ?
    wait your reply
    thx Sir

  • Krishna Ch

    how to delete the picture from the gallery with its folder after capturing the image and uploaded to server?

  • Teraiya Mayur

    is it Comptible with Android OS 7.0 ?

  • sawdroiddev

    Null Pointer Exception:-
    public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
    }

  • Sunche Khan

    Great totarial Ravi, works fine. But this Camera API(android.hardware.camera) has deprecated. Am kindly looking for a way to implement both camera’s APIs (android.hardware.camera and android.hardware.camera2) to support older and higher android versions. Any help will be helpful. Thank you

  • shweta

    🙁 using this code i got exception in android version 6.0

    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.news.cinepolis, PID: 9397
    java.lang.NullPointerException: file
    at android.net.Uri.fromFile(Uri.java:452)
    at com.news.cinepolis.MainActivity.getOutputMediaFileUri(MainActivity.java:243)
    at com.news.cinepolis.MainActivity.captureImage(MainActivity.java:104)
    at com.news.cinepolis.MainActivity.access$000(MainActivity.java:23)
    at com.news.cinepolis.MainActivity$1.onClick(MainActivity.java:58)

    • hafizh

      yeah..same with me, i got error on creating directory… have you solve that problem?

      (edited)..
      i add this additional request permission then calling it from onCreate and it works

      private void requestRuntimePermission() {
      if (Build.VERSION.SDK_INT >= 23) {
      if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
      != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(this,
      new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
      }
      }
      }

      • shweta

        exactly in marshmellow we need to provide additional permission in manifest as well as in our java class . i also use runtime permission in java class in onstart().
        this is my method.

        public void requestStoragePermission() {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
        }

        //And finally ask for the permission
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
        }

        //This method will be called when the user will tap on allow or deny
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        //Checking the request code of our request
        if (requestCode == STORAGE_PERMISSION_CODE) {

        //If permission is granted
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        // if(userChoosenTask.equals(“Choose from Library”))
        // galleryIntent();
        } else {
        //Displaying another toast if permission is not granted
        Toast.makeText(this, “Oops you just denied the permission”, Toast.LENGTH_LONG).show();
        }
        }
        }

  • Ronel Gonzales

    thanks

  • lowi adrian colinares

    Hey Mr. Ravi, your codes was very helpful and i would like to say thank you for sharing it to us, but i’ll only have one question, can you add some functions on how to scaled the image or lessen the file size or simply reduce the size of image before it save??? please do response, your response will be a big help not to me but also for them.

    • The image is already compressed in previewCapturedImage() function. Check the below link to see how to reduce the dimensions
      https://stackoverflow.com/questions/15759195/reduce-size-of-bitmap-to-some-specified-pixel-in-android

      • lowi adrian colinares

        Again Mr. Ravi, thanks for your great response, you’re so amazing, I believe that the higher InSampleSize value will reduce the dimension of the image, and I used it but the preview image display small size in the screen and still the file size of the image was big, and regarding to the link that you said, how to apply the method of reducing image size in your code? particularly on or before saving??? please do response again Mr Ravi. Thank you so much!!!

        • Alifia Choirunnisa

          hai adrian, i have same problem with you, have you solved it?

          • lowi adrian colinares

            Hi Alifia, I already solve it by creating a method that will scale down the actual size of image or simply reduce the actual file size of image before saving it to my phone storage. i used the method from the given link of Mr. Ravi but I also create a Save method and called the Scale Down method to use it and it will works.

          • Alifia Choirunnisa

            thanks adrian it’s work, I create a save method to save a small size and delete the big size file.
            I wan’t to ask again, from this tutorial we save file with custom name as we want, but can we save it with the real name of photo? @ravi8x:disqus @lowiadriancolinares:disqus

          • lowi adrian colinares

            its good to hear that you made the saving of scales size image 🙂 .

            yes, we save a custom filename as we want, but i believe that the real name of image was customised, so why would you like to get the real image name if you can make your own image name ???

          • Alifia Choirunnisa

            I use gps map camera application to get gps coordinate too from image metadata, but I don’t know how to get image metadata from android, so I want to get the gps coordinate from the real name. hehe 🙂
            But now it can solved with another way, I get the image metadata by exif in php code 🙂

          • lowi adrian colinares

            nice nice good job 🙂

    • Ogbonda Glory

      try compressing the image sent with this method

    • Ogbonda Glory

      private String decodeFile(String path, int DESIREDWIDTH, int DESIREDHEIGHT)
      {
      String strMyImagePath = null;
      Bitmap scaledBitmap = null;
      try {
      Bitmap unscaledBitmap = ScalingUtilities.decodeFile(path, DESIREDWIDTH, DESIREDHEIGHT, ScalingUtilities.ScalingLogic.FIT);
      if (!(unscaledBitmap.getWidth() <= DESIREDWIDTH && unscaledBitmap.getHeight() <= DESIREDHEIGHT)) {
      scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap, DESIREDWIDTH, DESIREDHEIGHT, ScalingUtilities.ScalingLogic.FIT);
      } else {
      unscaledBitmap.recycle();
      return path;
      }
      String extr = Environment.getExternalStorageDirectory().toString();
      File mFolder = new File(extr + "/TMMFOLDER");
      if (!mFolder.exists()) {
      mFolder.mkdir();
      }
      String filename= newString.substring(newString.lastIndexOf("/")+1);
      String s = filename;
      File f = new File(mFolder.getAbsolutePath(), s);
      strMyImagePath = f.getAbsolutePath();
      FileOutputStream fos = null;
      try {
      fos = new FileOutputStream(f);
      scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
      fos.flush();
      fos.close();
      } catch (FileNotFoundException e) {
      e.printStackTrace();
      } catch (Exception e) {
      e.printStackTrace();
      }
      scaledBitmap.recycle();
      } catch (Throwable e) {
      }
      if (strMyImagePath == null) {
      return path;
      }
      return strMyImagePath;
      }

    • Ogbonda Glory

      Then u can now call the method using ur imagePath

      imagePath= decodeFile(imagePath,400,400);

  • John Mann

    Hello Ravi, it’s very nice to have found this tutorial. Thanks.
    I took a photo using the compiled app but couldn’t find the photo file afterwards. It even didn’t show up among “Recents”. This is on a Samsung Galaxy Tab S2. I have an SD card installed. Can you help me out?

  • Edwin Gomez Ortega Callaú

    Good job, but if I want to save to internal storage what can I do?

  • Merve

    why photos look horizontally?how the photos always look vertical?

  • Mohd Qasim

    this code is giving exception in 6.0+ versions
    Failed to load module via V2: java.lang.ClassNotFoundException: Didn’t find class “com.google.android.gms.dynamite.DynamiteModule$DynamiteLoaderClassLoader” on path: DexPathList[[zip file “/data/app/com.example.ccs.loginapp2-1/base.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_dependencies_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_0_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_1_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_2_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_3_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_4_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_5_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_6_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_7_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_8_apk.apk”, zip file “/data/app/com.example.ccs.loginapp2-1/split_lib_slice_9_apk.apk”],nativeLibraryDirectories=[/data/app/com.example.ccs.loginapp2-1/lib/x86, /system/lib, /vendor/lib]]

  • Maki

    It does not save the image or video =(