Android Camera Tutorial Part 2

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 called Camera.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.NoMethod & Description
1getCameraInfo(int cameraId, Camera.CameraInfo cameraInfo)
It returns the information about a particular camera
2getNumberOfCameras()
It returns an integer number defining of cameras availaible on device
3lock()
It is used to lock the camera , so no other application can access it
4release()
It is used to release the lock on camera , so other applications can access it
5open(int cameraId)
It is used to open particular camera when multiple cameras are supported
6enableShutterSound(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
ClassDescription
CameraIt is used to control the camera and take images or capture video from the camera
SurfaceViewThis 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.NoMethod & Description
1startFaceDetection()
This function starts the face detection in the camera
2stopFaceDetection()
It is used to stop the face detection which is enabled by the above function
3startSmoothZoom(int value)
It takes an integer value and zoom the camera very smoothly to that value
4stopSmoothZoom()
It is used to stop the zoom of the camera
5stopPreview()
It is used to stop the preiview of the camera to the user
6takePicture(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
StepsDescription
1You 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.
2Modify src/MainActivity.java file to add the respective code of camera and get references to the XML components.
3Create a new ShowCamera.java file to extend it with SurfaceView and implement the SurfaceHolder interface .
4Modify 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.
5Modify res/values/strings.xml to define required constant values
6Modify AndroidManifest.xml as shown below to add the necessary permissions for camera
7Run 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 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 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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="horizontal" >

   <LinearLayout
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:layout_weight="0.30"
      android:orientation="vertical" >
        
         <FrameLayout
            android:id="@+id/camera_preview"
            android:layout_width="fill_parent"
            android:layout_height="199dp" />

         <Button
            android:id="@+id/button_capture"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="snapIt"
            android:text="@string/Capture" />

         <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="fitXY"
            android:src="@drawable/ic_launcher" />
   
   </LinearLayout>

< /LinearLayout>
Modify the content of the res/values/string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">Camera1</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="Capture">Capture</string>
    
</resources>
Modify the content of the AndroidManifest.xml and add the necessary permissions as shown below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.camera1"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />
   <uses-permission android:name="android.permission.CAMERA"/>
   <uses-feature android:name="android.hardware.camera" />
   <uses-feature android:name="android.hardware.camera.autofocus" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
         <activity
            android:name="com.example.camera1.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
               <action android:name="android.intent.action.MAIN" />

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

</manifest>
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 Eclipse Run Icon 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.

Anroid Camera Tutorial

Select your mobile device as an option and then check your mobile device which will display following screen:

Anroid Camera Tutorial

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.


You can  DOWNLOAD SAMPLE CODE  here

Comments