How to open camera in android using intent and display the captured image

In this tutorial,we will learn how to open camera in  an android using intent and display the captured image into the ImageView in your android application step by step with easy explanation.

We can open the camera using  ACTION_IMAGE_CAPTURE of the MediaStore class.

Let’s start

1. activity_camera.xml:

 In the activity_camera.xml contains one imageview and one button.

 Imageview is used for the display the captured image and button is used for the open the  camera.

2.MainActivity.java

This is the java class where we will implement the logic for open the camera in an android and display the captured image into the imageview.

Button onClickListener=Here we will open the camera using intent.

onActivityResult( )=Here we will get the captured image.

activity_camera.xml

<LinearLayout xmlns:androclass=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android layout_heigth=”wrap_content”
android Orientation=”Vertical”
android layout_width=”wrap_content”>
 
<ImageView
android id=”@+id/captured_image
android layout_heigth=”400dp”
android layout_width=”wrap_content”/>
 
<Button
android id=”@+id/open_camera
android layout_heigth=”wrap_content”
android layout_width=”wrap_content”/>
 
</LinearLayout>

MainActivity.Java

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;

Public class MainActivity extends Activity
{
ImageView displayImage;
Button openCamera;
private static int image_request_code=30;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);

displayImage=(ImageView)findViewById(R.id.captured_image);
openCamera=(Button)findViewById(R.id.open_camera);


openCamera.setOnClickListener(new View.OnClickListener
{
@Override
Public void onClick (View v)
{

//This is onClickListener where we will open the camera using intent.
Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,image_request_code);
}

});
}

//Here we will get the captured image and display into the imageview
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
if(requestcode==image_request_code)
{
Bitmap image=(Bitmap) data.getExtras( ).get(“data”);
displayImage.setImageBitmap(image); //Display image into the imageview
}
}

}

Output

Example of Android camera intent

Hope,I explained very well about  android camera and if you still have any  query,comment me.

Thanks and Regards

Placement preparation

sumankumar80

Hello Friends,I have written and developed this website because you can learn technology easily ,prepare for the placement and also for the any type of examination . By :Suman Kumar

Leave a Reply

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