How to use Android Camera Tutorial Code - Programming tutorials
These are the following two ways , in which you can use camera in your application
- Using existing android camera application in our application
- Directly using Camera API provided by android in our application
Using existing android camera application in our application
You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera application installed on your phone. Its syntax is given below
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Apart from the above , there are other availaible Intents provided by MediaStore. They are listed as follows
Sr.No | Intent type and description |
---|---|
1 | ACTION_IMAGE_CAPTURE_SECURE It returns the image captured from the camera , when the device is secured |
2 | ACTION_VIDEO_CAPTURE It calls the existing video application in android to capture video |
3 | EXTRA_SCREEN_ORIENTATION It is used to set the orientation of the screen to vertical or landscape |
4 | EXTRA_FULL_SCREEN It is used to control the user interface of the ViewImage |
5 | INTENT_ACTION_VIDEO_CAMERA This intent is used to launch the camea in the video mode |
6 | EXTRA_SIZE_LIMIT It is used to specify the size limit of video or image capture size |
Now you will use the function startActivityForResult() to launch this activity and wait for its result. Its syntax is given below
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main activity. There are methods defined in the activity class that does the same job , but used when you are not calling from the activity but from somewhere else. They are listed below
Sr.No | Activity function description |
---|---|
1 | startActivityForResult(Intent intent, int requestCode, Bundle options) It starts an activity , but can take extra bundle of options with it |
2 | startActivityFromChild(Activity child, Intent intent, int requestCode) It launch the activity when your activity is child of any other activity |
3 | startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options) It work same as above , but it can take extra values in the shape of bundle with it |
4 | startActivityFromFragment(Fragment fragment, Intent intent, int requestCode) It launches activity from the fragment you are currently inside |
5 | startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle options) It not only launches the activity from the fragment , but can take extra values with it |
No matter which function you used to launch the activity , they all return the result. The result can be obtained by overriding the function onActivityResult.
Example
Here is an example that shows how to launch the exisitng camera application to capture an image and display the result in the form of bitmap
To experiment with this example , you need to run this on an actual device on which camera is supported.
Steps | Description |
---|---|
1 | You will use Eclipse IDE to create an Android application and name it as Camera under a package com.example.camera. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs. |
2 | Modify src/MainActivity.java file to add intent code to launch the activity and result method to recieve the output. |
3 | Modify layout XML file res/layout/activity_main.xml add any GUI component if required. Here we add only imageView and a textView. |
4 | Modify res/values/strings.xml to define required constant values |
5 | Run the application and choose a running android device and install the application on it and verify the results. |
Following is the content of the modified main activity file src/com.example.camera/MainActivity.java.
package com.example.camera;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView imgFavorite;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgFavorite = (ImageView)findViewById(R.id.imageView1);
imgFavorite.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
open();
}
});
}
public void open(){
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap bp = (Bitmap) data.getExtras().get("data");
imgFavorite.setImageBitmap(bp);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Following will be the content of res/layout/activity_main.xml file:
Following will be the content of res/values/strings.xml to define one new constants
Camera
Settings
Hello world!
Tap the image to open the camera!!
Following is the default content of AndroidManifest.xml:
Let's try to run your Camera application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.
Select your mobile device as an option and then check your mobile device which will display following screen:
Now just tap on the image of android icon and the camera will be opened. Just capture a picture. After capturing it , two buttons will appear asking you to discard it or keep it
Just press the tic (green) button and you will be brought back to your application with the captured image inplace of android icon
Directly using Camera API provided by android in our application
We will be using the camera API to integrate the camera in our application
First you will need to intialize the camera object using the static method provide by the api calledCamera.open. Its syntax is
Camera object = null;
object = Camera.open();
Apart from the above function , there are other functions provided by the Camera class that which are listed below
Sr.No | Method & Description |
---|---|
1 | getCameraInfo(int cameraId, Camera.CameraInfo cameraInfo) It returns the information about a particular camera |
2 | getNumberOfCameras() It returns an integer number defining of cameras availaible on device |
3 | lock() It is used to lock the camera , so no other application can access it |
4 | release() It is used to release the lock on camera , so other applications can access it |
5 | open(int cameraId) It is used to open particular camera when multiple cameras are supported |
6 | enableShutterSound(boolean enabled) It is used to enable/disable default shutter sound of image capture |
Now you need make an seperate class and extend it with SurfaceView and implements SurfaceHolder interface.
The two classes that have been used have the following purpose
Class | Description |
---|---|
Camera | It is used to control the camera and take images or capture video from the camera |
SurfaceView | This class is used to present a live camera preview to the user. |
You have to call the preview method of the camera class to start the preview of the camera to the user
public class ShowCamera extends SurfaceView implements SurfaceHolder.Callback {
private Camera theCamera;
public void surfaceCreated(SurfaceHolder holder) {
theCamera.setPreviewDisplay(holder);
theCamera.startPreview();
}
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3){
}
public void surfaceDestroyed(SurfaceHolder arg0) {
}
}
Apart from the preview there are other options of the camera that can be set using the other functions provided by the Camera API
Sr.No | Method & Description |
---|---|
1 | startFaceDetection() This function starts the face detection in the camera |
2 | stopFaceDetection() It is used to stop the face detection which is enabled by the above function |
3 | startSmoothZoom(int value) It takes an integer value and zoom the camera very smoothly to that value |
4 | stopSmoothZoom() It is used to stop the zoom of the camera |
5 | stopPreview() It is used to stop the preiview of the camera to the user |
6 | takePicture(Camera.ShutterCallback shutter, Camera.PictureCallback raw, Camera.PictureCallback jpeg) It is used to enable/disable default shutter sound of image capture |
Example
Following example demonstrates the usage of the camera API in the application
To experiment with this example, you will need actual Mobile device equipped with latest Android OS, beacuse camera is not supported by the emulator
Steps | Description |
---|---|
1 | You will use Eclipse IDE to create an Android application and name it as Camera under a package com.example.camera1. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs. |
2 | Modify src/MainActivity.java file to add the respective code of camera and get references to the XML components. |
3 | Create a new ShowCamera.java file to extend it with SurfaceView and implement the SurfaceHolder interface . |
4 | Modify layout XML file res/layout/activity_main.xml add any GUI component if required. Here we add only FrameView and a button and a ImageView. |
5 | Modify res/values/strings.xml to define required constant values |
6 | Modify AndroidManifest.xml as shown below to add the necessary permissions for camera |
7 | Run the application and choose a running android device and install the application on it and verify the results. |
Following is the content of the modified main activity file src/com.example.camera1/MainActivity.java.
package com.example.camera1;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Camera cameraObject;
private ShowCamera showCamera;
private ImageView pic;
public static Camera isCameraAvailiable(){
Camera object = null;
try {
object = Camera.open();
}
catch (Exception e){
}
return object;
}
private PictureCallback capturedIt = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
if(bitmap==null){
Toast.makeText(getApplicationContext(), "not taken", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "taken", Toast.LENGTH_SHORT).show();
}
cameraObject.release();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic = (ImageView)findViewById(R.id.imageView1);
cameraObject = isCameraAvailiable();
showCamera = new ShowCamera(this, cameraObject);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(showCamera);
}
public void snapIt(View view){
cameraObject.takePicture(null, null, capturedIt);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Create the new java file called assrc/com.example.camera1/ShowCamera.java. and add the following code
package com.example.camera1;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class ShowCamera extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holdMe;
private Camera theCamera;
public ShowCamera(Context context,Camera camera) {
super(context);
theCamera = camera;
holdMe = getHolder();
holdMe.addCallback(this);
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
theCamera.setPreviewDisplay(holder);
theCamera.startPreview();
} catch (IOException e) {
}
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
}
Modify the content of the res/layout/activity_main.xml
< /LinearLayout>
Modify the content of the res/values/string.xml
Camera1
Settings
Hello world!
Capture
Modify the content of the AndroidManifest.xml and add the necessary permissions as shown below.
Let's try to run your SendSMSDemo application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.
Select your mobile device as an option and then check your mobile device which will display following screen:
The camera would start showing its preview in the upper half panel. Just click the capture button. You can now either store the captured image , upload it to the web or either discard it.