Android camera example

In this Android tip, I am going to provide you an example of integrating Camera to your application so the user can take, view, and save picture to a file.
In Android, there are two different methods to integrate Camera to your application. One method uses the built-in Camera application. Another method uses Camera API. In this tip, the latter will be implemented.



To integrate Camera in your application using Camera API, in your code, you need to create an instance of Camera class using its static method open() or open(int CameraID). Some Android phones (e.g. The Galaxy Grand Max, Galaxy A5) have two cameras: front-facing and back cameras. With the open (int CameraID) method, you can specify the camera to be used. Typically before taking a picture, camera allows to preview the picture. You will create a class that extends the SurfaceView class. An instance of the class is used to preview the picture. To take the picture, you simply call the takePicture (Camera.ShutterCallback shutter, Camera.PictureCallback raw, Camera.PictureCallback jpeg) method of the Camera object. It takes three parameters. The first parameter signals the motion of picture capture. The second and third parameters are Callback interface used to supply image data from a photo capture. The first and second parameters can be null.
Now to have an example application on using Camera API, you create a new Android project. Then, in the activity_main.xml file, you add a FrameLayout, a Button, and an ImageView.

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
>

  
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    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="takePhoto"
        android:text="Take picture" />

      <ImageView
        android:id="@+id/img_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitXY" />
    
  </LinearLayout>


</RelativeLayout>


Here is the code written in the MainActivity class to use Camera API to allow the user to preview, take, and save a picture to a file. After the first picture capture, the camera is reset to allow you to take another picture.


public class MainActivity extends Activity {

  private Camera cameraObject;
  private CameraView cameraView;
  private ImageView pic;
  private Handler handler;
  FrameLayout preview;
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    pic = (ImageView)findViewById(R.id.img_view);
    handler=new Handler();
  }
  
  private Camera getCamera() {
     int cameraId = -1;
     Camera object = null;
     // Search for front or back camera
     int numberOfCameras = Camera.getNumberOfCameras();
     for (int i = 0; i < numberOfCameras; i++) {
      CameraInfo info = new CameraInfo();
      Camera.getCameraInfo(i, info);
      if (info.facing == CameraInfo.CAMERA_FACING_FRONT || info.facing==CameraInfo.CAMERA_FACING_BACK) {
       cameraId = i;
       break;
      }
     }
     if(cameraId>=0) object=Camera.open(cameraId);
     return object;
   }

  // Callback interface used to supply image data from a photo capture.
  private PictureCallback PCallback= new PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

    Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
    if(bitmap==null){  
      Toast.makeText(getApplicationContext(), "Photo not taken", Toast.LENGTH_SHORT).show();
    }
    else
    {
   // Show image
   pic.setImageBitmap(bitmap);
   // Save to file  
   FileOutputStream outStream = null;
       try {
          
           outStream = new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+System.currentTimeMillis()+".jpg");
           outStream.write(data);
           outStream.close();
          
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }

    
    }
    
    // Release camera
    releaseCamera();
    // Reset camera after a short time period
    handler.postDelayed(new Runnable(){
   public void run(){
   // reset camera and preview
   initCamera();
  
   }
    }, 300);
    
  }
};
  // Get camera object and prepare preview
  public void initCamera(){
   cameraObject = getCamera();
    cameraView = new CameraView(this, cameraObject);
    preview = (FrameLayout) findViewById(R.id.camera_preview);
    preview.addView(cameraView);
    
    
  }
  public void takePhoto(View view){
    cameraObject.takePicture(null, null, PCallback);
  }
  
  protected void onResume(){
  super.onResume();
  initCamera();  
  
  }
  
  public void releaseCamera(){
  if(cameraObject!=null){
  // Release camera and remove surface view from the preview
  cameraObject.release();
  cameraObject=null;
  preview.removeAllViews();
  }
  }
  
  // Camera preview
  private class CameraView extends SurfaceView implements SurfaceHolder.Callback {

  private SurfaceHolder surfaceHolder;
  private Camera camera;

  public CameraView(Context context,Camera camera) {
    super(context);
    this.camera = camera;
    surfaceHolder = getHolder();
    surfaceHolder.addCallback(this);
  }

  @Override
  public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {

  }
  
  @Override
  public void surfaceCreated(SurfaceHolder holder) {
    try  {
   if (Build.VERSION.SDK_INT >= 8) {
   camera.setDisplayOrientation(90);
   }
  
   camera.setPreviewDisplay(holder);
   camera.startPreview();
     } catch (IOException e) {
    }
  }

  @Override
  public void surfaceDestroyed(SurfaceHolder arg0) {
  }

}

  protected void onPause(){
  super.onPause();
  releaseCamera();
  }
}

Before you run the example application, do not forget to add the following lines of code to AndroidManifest.xml file.

  <uses-permission android:name="android.permission.CAMERA"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-feature android:name="android.hardware.camera" />
  <uses-feature android:name="android.hardware.camera.autofocus" />



Android-camera-example

Posted by: Dara | post date: 01-20-2015 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.