Android Camera Example

This tutorial shows how to launch camera in android, capture an image, and display the captured image in an ImageView. It is easy, just follow the steps given below.

Step 1: Create a new project with name CameraExample and package name com.myexample.camera. Select File/New/New Project. Fill the forms and click “Finish” button.

Step 2: Open res/layout/xml (or) main.xml and add following code. Here we will add a Button for launching camera, and an ImageView for displaying the captured image.

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:gravity="center"
	android:padding="10dp"
	android:orientation="vertical">

	<Button
		android:layout_height="wrap_content"
		android:layout_width="match_parent"
		android:text="TAKE PICTURE"
		android:id="@+id/mainButton1"/>

	<ImageView
		android:layout_height="match_parent"
		android:layout_width="match_parent"
		android:scaleType="fitCenter"
		android:id="@+id/mainImageView1"/>

</LinearLayout>

Step 3: Open app/src/main/java/package and open MainActivity.java. Add following code in it. Here when the Button is clicked, we start an Intent to launch the camera and get results. And when the image is captured, we get the results of the Intent operation, convert it to a Bitmap image, and display the Bitmap image in an ImageView.

package com.myexample.camera;

import android.app.*;
import android.os.*;
import android.widget.*;
import android.view.*;
import android.content.*;
import android.provider.*;
import android.graphics.*;

public class MainActivity extends Activity 
{
	private Button button1;
	private ImageView imageview1;
	private static final int CAMERA_REQUEST = 1;
	
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		
		button1 = findViewById(R.id.mainButton1);
		imageview1 = findViewById(R.id.mainImageView1);
		
		button1.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v){
				// Start an Intent to Capture image and get results of the action
				Intent myintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(myintent, CAMERA_REQUEST);
			}
		});
		
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		// Get the image, from the Activity opened by intent, in the form of a Bitmap
		if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK){
			Bitmap photo = (Bitmap) data.getExtras().get("data");
			// Display the Bitmap image in imageview1
			imageview1.setImageBitmap(photo);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
}

Output:
Now run the app. Here when the Button is clicked, the app will launch camera, and the captured image will be displayed in the ImageView.