How to Make a Custom Camera in Android

In this article you will learn how to make a custom camera in Android.

Today I will share a new article, this is on the camera in Android.

This article shows how to make a custom camera in Android and how to save the image in the gallery that's captured by the custom camera.

For this first off make the Layout XML file in the resource folder. The code is shown below.

  1. camerademo_activity.xml  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent" >  
  6.   
  7.     <SurfaceView  
  8.         android:id="@+id/surfaceView"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="fill_parent" />  
  11.   
  12.     <TextView  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_centerInParent="true"  
  16.         android:text="Camera Demo application\nDeveloped by Ravi Sharma"  
  17.         android:textColor="@android:color/black" />  
  18.   
  19.     <Button  
  20.         android:id="@+id/captureImage"  
  21.         android:layout_width="wrap_content"  
  22.         android:layout_height="wrap_content"  
  23.         android:layout_alignParentBottom="true"  
  24.         android:layout_centerHorizontal="true"  
  25.         android:layout_marginBottom="@dimen/activity_vertical_margin"  
  26.         android:background="@drawable/btn_broadcast_selected" />  
  27.   
  28.     <Button  
  29.         android:id="@+id/flash"  
  30.         android:layout_width="wrap_content"  
  31.         android:layout_height="wrap_content"  
  32.         android:layout_alignParentBottom="true"  
  33.         android:layout_marginBottom="@dimen/activity_vertical_margin"  
  34.         android:layout_marginRight="25dp"  
  35.         android:layout_toLeftOf="@id/captureImage"  
  36.         android:background="@drawable/btn_flash" />  
  37.   
  38.     <Button  
  39.         android:id="@+id/flipCamera"  
  40.         android:layout_width="wrap_content"  
  41.         android:layout_height="wrap_content"  
  42.         android:layout_alignParentBottom="true"  
  43.         android:layout_marginBottom="@dimen/activity_vertical_margin"  
  44.         android:layout_marginLeft="25dp"  
  45.         android:layout_toRightOf="@id/captureImage"  
  46.         android:background="@drawable/btn_flipcamera" />  
  47.   
  48. </RelativeLayout>  
In the XML file there are the following three buttons: 
  • One for capturing the image.
  • One for turning on/off the flash (if the device supports it).
  • One to change the camera (back or front).

The surface view shows the camera to be displayed on the screen.

For this make a CameraDemoActivity.java class and extend it with activity and override the onCreate method and make the object of all the Buttons and SurfaceView.

  1. public class CameraDemoActivity extends Activity{  
  2. private SurfaceView surfaceView;  
  3.     private SurfaceHolder surfaceHolder;  
  4.     private Camera camera;  
  5.     private Button flipCamera;  
  6.     private Button flashCameraButton;  
  7.     private Button captureImage;  
  8.     private int cameraId;  
  9.     private boolean flashmode = false;  
  10.     private int rotation;  
  11.   
  12.   
  13. @Override  
  14.     protected void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.camerademo_activity);  
  17.         // camera surface view created  
  18.         cameraId = CameraInfo.CAMERA_FACING_BACK;  
  19.         flipCamera = (Button) findViewById(R.id.flipCamera);  
  20.         flashCameraButton = (Button) findViewById(R.id.flash);  
  21.         captureImage = (Button) findViewById(R.id.captureImage);  
  22.         surfaceView = (SurfaceView) findViewById(R.id.surfaceView);  
  23.               
  24.     }  
  25. }  
After this make the SurfaceHolder object and add the callback with SurfaceHolder and add the listener with a button. For doing that you must implement the onClickListener and Callback (for SurfaceHolder).
  1. public class CameraDemoActivity extends Activity implements Callback,  
  2.         OnClickListener  
And put the code in the onCreate method below the earlier code.
  1. surfaceHolder = surfaceView.getHolder();  
  2. surfaceHolder.addCallback(this);  
  3. flipCamera.setOnClickListener(this);  
  4. captureImage.setOnClickListener(this);  
  5. flashCameraButton.setOnClickListener(this);  
  6. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);  
The last line of the preceding code is used to keep the screen on until the activity is running.

Now we need to check the number of the camera in the device and check whether or not the device has a flash.

Use the following code in the onCreate methiod.
  1. if (Camera.getNumberOfCameras() > 1) {  
  2.             flipCamera.setVisibility(View.VISIBLE);  
  3.         }  
  4.         if (!getBaseContext().getPackageManager().hasSystemFeature(  
  5.                 PackageManager.FEATURE_CAMERA_FLASH)) {  
  6.             flashCameraButton.setVisibility(View.GONE);  
  7.         }  
After adding the callback on the surfaceHolder object you should override the three methods.

All three are below.
  1. @Override  
  2.     public void surfaceCreated(SurfaceHolder holder) {  
  3.           
  4.     }  
  5. @Override  
  6.     public void surfaceChanged(SurfaceHolder holder, int format, int width,  
  7.             int height) {  
  8.   
  9.     }  
  10.   
  11.     @Override  
  12.     public void surfaceDestroyed(SurfaceHolder holder) {  
  13.   
  14.     }  
In all these three methods we only used the surfaceCreated method as in the following:
  1. @Override  
  2.     public void surfaceCreated(SurfaceHolder holder) {  
  3.         if (!openCamera(CameraInfo.CAMERA_FACING_BACK)) {  
  4.             alertCameraDialog ();  
  5.         }  
  6.   
  7.     }  
There are two methods. One is to open the camera and the second is alertCameraDialog. The openCameera method opens the camera and if there is an issue then alertCameraDialog is called.

First off all discuss the alertCameraDialog method. This method is only used to show the message “error to open camera”.
  1. private void alertCameraDialog() {  
  2.         AlertDialog.Builder dialog = createAlert(CameraDemoActivity.this,  
  3.                 "Camera info""error to open camera");  
  4.         dialog.setNegativeButton("OK"new DialogInterface.OnClickListener() {  
  5.             @Override  
  6.             public void onClick(DialogInterface dialog, int which) {  
  7.                 dialog.cancel();  
  8.   
  9.             }  
  10.         });  
  11.   
  12.         dialog.show();  
  13.     }  
Now focus on the open camera method as in the following:
  1. private boolean openCamera(int id) {  
  2.         boolean result = false;  
  3.         cameraId = id;  
  4.         releaseCamera();  
  5.         try {  
  6.             camera = Camera.open(cameraId);  
  7.         } catch (Exception e) {  
  8.             e.printStackTrace();  
  9.         }  
  10.         if (camera != null) {  
  11.             try {  
  12.                 setUpCamera(camera);  
  13.                 camera.setErrorCallback(new ErrorCallback() {  
  14.   
  15.                     @Override  
  16.                     public void onError(int error, Camera camera) {  
  17. //to show the error message.  
  18.                     }  
  19.                 });  
  20.                 camera.setPreviewDisplay(surfaceHolder);  
  21.                 camera.startPreview();  
  22.                 result = true;  
  23.             } catch (IOException e) {  
  24.                 e.printStackTrace();  
  25.                 result = false;  
  26.                 releaseCamera();  
  27.             }  
  28.         }  
  29.         return result;  
  30.     }  
In this method we get the cameraid as a parameter and pass it to open the camera.

There is another method to release the camera, in other words stop whichever camera is running (back or front) and make the camera object null for further use.
  1. private void releaseCamera() {  
  2.         try {  
  3.             if (camera != null) {  
  4.                 camera.setPreviewCallback(null);  
  5.                 camera.setErrorCallback(null);  
  6.                 camera.stopPreview();  
  7.                 camera.release();  
  8.                 camera = null;  
  9.             }  
  10.         } catch (Exception e) {  
  11.             e.printStackTrace();  
  12.             Log.e("error", e.toString());  
  13.             camera = null;  
  14.         }  
  15.     }  
Another important method in this is setUpCamera that gets the camera object as a parameter. In this method we manage the rotation and the flash button also because the front camera doesn't support a flash.
  1. private void setUpCamera(Camera c) {  
  2.     Camera.CameraInfo info = new Camera.CameraInfo();  
  3.     Camera.getCameraInfo(cameraId, info);  
  4.     rotation = getWindowManager().getDefaultDisplay().getRotation();  
  5.     int degree = 0;  
  6.     switch (rotation) {  
  7.     case Surface.ROTATION_0:  
  8.         degree = 0;  
  9.         break;  
  10.     case Surface.ROTATION_90:  
  11.         degree = 90;  
  12.         break;  
  13.     case Surface.ROTATION_180:  
  14.         degree = 180;  
  15.         break;  
  16.     case Surface.ROTATION_270:  
  17.         degree = 270;  
  18.         break;  
  19.   
  20.     default:  
  21.         break;  
  22.     }  
  23.   
  24.     if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {  
  25.         // frontFacing  
  26.         rotation = (info.orientation + degree) % 330;  
  27.         rotation = (360 - rotation) % 360;  
  28.     } else {  
  29.         // Back-facing  
  30.         rotation = (info.orientation - degree + 360) % 360;  
  31.     }  
  32.     c.setDisplayOrientation(rotation);  
  33.     Parameters params = c.getParameters();  
  34.   
  35.     showFlashButton(params);  
  36.   
  37.     List<String> focusModes = params.getSupportedFlashModes();  
  38.     if (focusModes != null) {  
  39.         if (focusModes  
  40.                 .contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {  
  41.             params.setFlashMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);  
  42.         }  
  43.     }  
  44.   
  45.     params.setRotation(rotation);  
  46. }  
To manage the flash there is a method “showFlashButton(params)”.
  1. private void showFlashButton(Parameters params) {  
  2.         boolean showFlash = (getPackageManager().hasSystemFeature(  
  3.                 PackageManager.FEATURE_CAMERA_FLASH) && params.getFlashMode() != null)  
  4.                 && params.getSupportedFlashModes() != null  
  5.                 && params.getSupportedFocusModes().size() > 1;  
  6.   
  7.         flashCameraButton.setVisibility(showFlash ? View.VISIBLE  
  8.                 : View.INVISIBLE);  
  9.   
  10.     }  
Override on the onClick(View v) method.

And use the code below:
  1. @Override  
  2.     public void onClick(View v) {  
  3.         switch (v.getId()) {  
  4.         case R.id.flash:  
  5.             flashOnButton();  
  6.             break;  
  7.         case R.id.flipCamera:  
  8.             flipCamera();  
  9.             break;  
  10.         case R.id.captureImage:  
  11.             takeImage();  
  12.             break;  
  13.   
  14.         default:  
  15.             break;  
  16.         }  
  17.     }  
There are three options in the onClick method, Flash, Flip camera and click the image.

The following code is for the flash on the camera.
  1. private void flashOnButton() {  
  2.     if (camera != null) {  
  3.         try {  
  4.             Parameters param = camera.getParameters();  
  5.             param.setFlashMode(!flashmode ? Parameters.FLASH_MODE_TORCH  
  6.                     : Parameters.FLASH_MODE_OFF);  
  7.             camera.setParameters(param);  
  8.             flashmode = !flashmode;  
  9.         } catch (Exception e) {  
  10.             // TODO: handle exception  
  11.         }  
  12.   
  13.     }  
  14. }  
And the Flip Camera method is given below:
  1. private void flipCamera() {  
  2.     int id = (cameraId == CameraInfo.CAMERA_FACING_BACK ? CameraInfo.CAMERA_FACING_FRONT  
  3.             : CameraInfo.CAMERA_FACING_BACK);  
  4.     if (!openCamera(id)) {  
  5.         alertCameraDialog();  
  6.     }  
  7. }  
Then the following is the main method of the activity to capture the image.
  1. private void takeImage() {  
  2.         camera.takePicture(nullnullnew PictureCallback() {  
  3.   
  4.             private File imageFile;  
  5.   
  6.             @Override  
  7.             public void onPictureTaken(byte[] data, Camera camera) {  
  8.                 try {  
  9.                     // convert byte array into bitmap  
  10.                     Bitmap loadedImage = BitmapFactory.decodeByteArray(data, 0,  
  11.                             data.length);  
  12.   
  13.                     // rotate Image  
  14.                     Matrix rotateMatrix = new Matrix();  
  15.                     rotateMatrix.postRotate(rotation);  
  16.                     Bitmap rotatedBitmap = Bitmap.createBitmap(loadedImage, 0,  
  17.                             0, loadedImage.getWidth(), loadedImage.getHeight(),  
  18.                             rotateMatrix, false);  
  19.                     String state = Environment.getExternalStorageState();  
  20.                     File folder = null;  
  21.                     if (state.contains(Environment.MEDIA_MOUNTED)) {  
  22.                         folder = new File(Environment  
  23.                                 .getExternalStorageDirectory() + "/Demo");  
  24.                     } else {  
  25.                         folder = new File(Environment  
  26.                                 .getExternalStorageDirectory() + "/Demo");  
  27.                     }  
  28.   
  29.                     boolean success = true;  
  30.                     if (!folder.exists()) {  
  31.                         success = folder.mkdirs();  
  32.                     }  
  33.                     if (success) {  
  34.                         java.util.Date date = new java.util.Date();  
  35.                         imageFile = new File(folder.getAbsolutePath()  
  36.                                 + File.separator  
  37.                                 + new Timestamp(date.getTime()).toString()  
  38.                                 + "Image.jpg");  
  39.   
  40.                         imageFile.createNewFile();  
  41.                     } else {  
  42.                         Toast.makeText(getBaseContext(), "Image Not saved",  
  43.                                 Toast.LENGTH_SHORT).show();  
  44.                         return;  
  45.                     }  
  46.   
  47.                     ByteArrayOutputStream ostream = new ByteArrayOutputStream();  
  48.   
  49.                     // save image into gallery  
  50.                     rotatedBitmap.compress(CompressFormat.JPEG, 100, ostream);  
  51.   
  52.                     FileOutputStream fout = new FileOutputStream(imageFile);  
  53.                     fout.write(ostream.toByteArray());  
  54.                     fout.close();  
  55.                     ContentValues values = new ContentValues();  
  56.   
  57.                     values.put(Images.Media.DATE_TAKEN,  
  58.                             System.currentTimeMillis());  
  59.                     values.put(Images.Media.MIME_TYPE, "image/jpeg");  
  60.                     values.put(MediaStore.MediaColumns.DATA,  
  61.                             imageFile.getAbsolutePath());  
  62.   
  63.                     CameraDemoActivity.this.getContentResolver().insert(  
  64.                             Images.Media.EXTERNAL_CONTENT_URI, values);  
  65.   
  66.                 } catch (Exception e) {  
  67.                     e.printStackTrace();  
  68.                 }  
  69.   
  70.             }  
  71.         });  
  72.     }  
Now we need to add some permission in the manifest file.

These are:
  1. <uses-feature android:name="android.hardware.camera" />  
  2.   
  3. <uses-permission android:name="android.permission.CAMERA" />  
  4. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
  5. <uses-permission  
  6.     android:name="android.permission.FLASHLIGHT"  
  7.     android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"  
  8.     android:protectionLevel="normal" />  
Some devices show the out of memory error. To avoid this add this line in the application tag:
  1. <application  
  2. .  
  3. .  
  4. .  
  5.    android:largeHeap="true"  
  6.         android:theme="@style/AppTheme" >  
The output of the application looks like this:

custom camara

The complete code of the entire Activity isthe following.
  1. package com.example.customcamera;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6.   
  7. import java.sql.Timestamp;  
  8. import java.util.List;  
  9.   
  10. import android.app.Activity;  
  11. import android.app.AlertDialog;  
  12. import android.app.AlertDialog.Builder;  
  13. import android.content.ContentValues;  
  14. import android.content.Context;  
  15. import android.content.DialogInterface;  
  16. import android.content.pm.PackageManager;  
  17. import android.graphics.Bitmap;  
  18. import android.graphics.Bitmap.CompressFormat;  
  19. import android.graphics.BitmapFactory;  
  20. import android.graphics.Matrix;  
  21. import android.hardware.Camera;  
  22. import android.hardware.Camera.CameraInfo;  
  23. import android.hardware.Camera.ErrorCallback;  
  24. import android.hardware.Camera.Parameters;  
  25. import android.hardware.Camera.PictureCallback;  
  26. import android.os.Bundle;  
  27. import android.os.Environment;  
  28. import android.provider.MediaStore;  
  29. import android.provider.MediaStore.Images;  
  30. import android.util.Log;  
  31. import android.view.ContextThemeWrapper;  
  32. import android.view.Surface;  
  33. import android.view.SurfaceHolder;  
  34. import android.view.SurfaceHolder.Callback;  
  35. import android.view.SurfaceView;  
  36. import android.view.View;  
  37. import android.view.View.OnClickListener;  
  38. import android.view.WindowManager;  
  39. import android.widget.Button;  
  40. import android.widget.Toast;  
  41.   
  42. public class CameraDemoActivity extends Activity implements Callback,  
  43.         OnClickListener {  
  44.   
  45.     private SurfaceView surfaceView;  
  46.     private SurfaceHolder surfaceHolder;  
  47.     private Camera camera;  
  48.     private Button flipCamera;  
  49.     private Button flashCameraButton;  
  50.     private Button captureImage;  
  51.     private int cameraId;  
  52.     private boolean flashmode = false;  
  53.     private int rotation;  
  54.   
  55.     @Override  
  56.     protected void onCreate(Bundle savedInstanceState) {  
  57.         super.onCreate(savedInstanceState);  
  58.         setContentView(R.layout.camerademo_activity);  
  59.         // camera surface view created  
  60.         cameraId = CameraInfo.CAMERA_FACING_BACK;  
  61.         flipCamera = (Button) findViewById(R.id.flipCamera);  
  62.         flashCameraButton = (Button) findViewById(R.id.flash);  
  63.         captureImage = (Button) findViewById(R.id.captureImage);  
  64.         surfaceView = (SurfaceView) findViewById(R.id.surfaceView);  
  65.         surfaceHolder = surfaceView.getHolder();  
  66.         surfaceHolder.addCallback(this);  
  67.         flipCamera.setOnClickListener(this);  
  68.         captureImage.setOnClickListener(this);  
  69.         flashCameraButton.setOnClickListener(this);  
  70.         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);  
  71.   
  72.         if (Camera.getNumberOfCameras() > 1) {  
  73.             flipCamera.setVisibility(View.VISIBLE);  
  74.         }  
  75.         if (!getBaseContext().getPackageManager().hasSystemFeature(  
  76.                 PackageManager.FEATURE_CAMERA_FLASH)) {  
  77.             flashCameraButton.setVisibility(View.GONE);  
  78.         }  
  79.     }  
  80.   
  81.     @Override  
  82.     public void surfaceCreated(SurfaceHolder holder) {  
  83.         if (!openCamera(CameraInfo.CAMERA_FACING_BACK)) {  
  84.             alertCameraDialog();  
  85.         }  
  86.   
  87.     }  
  88.   
  89.     private boolean openCamera(int id) {  
  90.         boolean result = false;  
  91.         cameraId = id;  
  92.         releaseCamera();  
  93.         try {  
  94.             camera = Camera.open(cameraId);  
  95.         } catch (Exception e) {  
  96.             e.printStackTrace();  
  97.         }  
  98.         if (camera != null) {  
  99.             try {  
  100.                 setUpCamera(camera);  
  101.                 camera.setErrorCallback(new ErrorCallback() {  
  102.   
  103.                     @Override  
  104.                     public void onError(int error, Camera camera) {  
  105.   
  106.                     }  
  107.                 });  
  108.                 camera.setPreviewDisplay(surfaceHolder);  
  109.                 camera.startPreview();  
  110.                 result = true;  
  111.             } catch (IOException e) {  
  112.                 e.printStackTrace();  
  113.                 result = false;  
  114.                 releaseCamera();  
  115.             }  
  116.         }  
  117.         return result;  
  118.     }  
  119.   
  120.     private void setUpCamera(Camera c) {  
  121.         Camera.CameraInfo info = new Camera.CameraInfo();  
  122.         Camera.getCameraInfo(cameraId, info);  
  123.         rotation = getWindowManager().getDefaultDisplay().getRotation();  
  124.         int degree = 0;  
  125.         switch (rotation) {  
  126.         case Surface.ROTATION_0:  
  127.             degree = 0;  
  128.             break;  
  129.         case Surface.ROTATION_90:  
  130.             degree = 90;  
  131.             break;  
  132.         case Surface.ROTATION_180:  
  133.             degree = 180;  
  134.             break;  
  135.         case Surface.ROTATION_270:  
  136.             degree = 270;  
  137.             break;  
  138.   
  139.         default:  
  140.             break;  
  141.         }  
  142.   
  143.         if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {  
  144.             // frontFacing  
  145.             rotation = (info.orientation + degree) % 330;  
  146.             rotation = (360 - rotation) % 360;  
  147.         } else {  
  148.             // Back-facing  
  149.             rotation = (info.orientation - degree + 360) % 360;  
  150.         }  
  151.         c.setDisplayOrientation(rotation);  
  152.         Parameters params = c.getParameters();  
  153.   
  154.         showFlashButton(params);  
  155.   
  156.         List<String> focusModes = params.getSupportedFlashModes();  
  157.         if (focusModes != null) {  
  158.             if (focusModes  
  159.                     .contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {  
  160.                 params.setFlashMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);  
  161.             }  
  162.         }  
  163.   
  164.         params.setRotation(rotation);  
  165.     }  
  166.   
  167.     private void showFlashButton(Parameters params) {  
  168.         boolean showFlash = (getPackageManager().hasSystemFeature(  
  169.                 PackageManager.FEATURE_CAMERA_FLASH) && params.getFlashMode() != null)  
  170.                 && params.getSupportedFlashModes() != null  
  171.                 && params.getSupportedFocusModes().size() > 1;  
  172.   
  173.         flashCameraButton.setVisibility(showFlash ? View.VISIBLE  
  174.                 : View.INVISIBLE);  
  175.   
  176.     }  
  177.   
  178.     private void releaseCamera() {  
  179.         try {  
  180.             if (camera != null) {  
  181.                 camera.setPreviewCallback(null);  
  182.                 camera.setErrorCallback(null);  
  183.                 camera.stopPreview();  
  184.                 camera.release();  
  185.                 camera = null;  
  186.             }  
  187.         } catch (Exception e) {  
  188.             e.printStackTrace();  
  189.             Log.e("error", e.toString());  
  190.             camera = null;  
  191.         }  
  192.     }  
  193.   
  194.     @Override  
  195.     public void surfaceChanged(SurfaceHolder holder, int format, int width,  
  196.             int height) {  
  197.   
  198.     }  
  199.   
  200.     @Override  
  201.     public void surfaceDestroyed(SurfaceHolder holder) {  
  202.   
  203.     }  
  204.   
  205.     @Override  
  206.     public void onClick(View v) {  
  207.         switch (v.getId()) {  
  208.         case R.id.flash:  
  209.             flashOnButton();  
  210.             break;  
  211.         case R.id.flipCamera:  
  212.             flipCamera();  
  213.             break;  
  214.         case R.id.captureImage:  
  215.             takeImage();  
  216.             break;  
  217.   
  218.         default:  
  219.             break;  
  220.         }  
  221.     }  
  222.   
  223.     private void takeImage() {  
  224.         camera.takePicture(nullnullnew PictureCallback() {  
  225.   
  226.             private File imageFile;  
  227.   
  228.             @Override  
  229.             public void onPictureTaken(byte[] data, Camera camera) {  
  230.                 try {  
  231.                     // convert byte array into bitmap  
  232.                     Bitmap loadedImage = null;  
  233.                     Bitmap rotatedBitmap = null;  
  234.                     loadedImage = BitmapFactory.decodeByteArray(data, 0,  
  235.                             data.length);  
  236.   
  237.                     // rotate Image  
  238.                     Matrix rotateMatrix = new Matrix();  
  239.                     rotateMatrix.postRotate(rotation);  
  240.                     rotatedBitmap = Bitmap.createBitmap(loadedImage, 00,  
  241.                             loadedImage.getWidth(), loadedImage.getHeight(),  
  242.                             rotateMatrix, false);  
  243.                     String state = Environment.getExternalStorageState();  
  244.                     File folder = null;  
  245.                     if (state.contains(Environment.MEDIA_MOUNTED)) {  
  246.                         folder = new File(Environment  
  247.                                 .getExternalStorageDirectory() + "/Demo");  
  248.                     } else {  
  249.                         folder = new File(Environment  
  250.                                 .getExternalStorageDirectory() + "/Demo");  
  251.                     }  
  252.   
  253.                     boolean success = true;  
  254.                     if (!folder.exists()) {  
  255.                         success = folder.mkdirs();  
  256.                     }  
  257.                     if (success) {  
  258.                         java.util.Date date = new java.util.Date();  
  259.                         imageFile = new File(folder.getAbsolutePath()  
  260.                                 + File.separator  
  261.                                 + new Timestamp(date.getTime()).toString()  
  262.                                 + "Image.jpg");  
  263.   
  264.                         imageFile.createNewFile();  
  265.                     } else {  
  266.                         Toast.makeText(getBaseContext(), "Image Not saved",  
  267.                                 Toast.LENGTH_SHORT).show();  
  268.                         return;  
  269.                     }  
  270.   
  271.                     ByteArrayOutputStream ostream = new ByteArrayOutputStream();  
  272.   
  273.                     // save image into gallery  
  274.                     rotatedBitmap.compress(CompressFormat.JPEG, 100, ostream);  
  275.   
  276.                     FileOutputStream fout = new FileOutputStream(imageFile);  
  277.                     fout.write(ostream.toByteArray());  
  278.                     fout.close();  
  279.                     ContentValues values = new ContentValues();  
  280.   
  281.                     values.put(Images.Media.DATE_TAKEN,  
  282.                             System.currentTimeMillis());  
  283.                     values.put(Images.Media.MIME_TYPE, "image/jpeg");  
  284.                     values.put(MediaStore.MediaColumns.DATA,  
  285.                             imageFile.getAbsolutePath());  
  286.   
  287.                     CameraDemoActivity.this.getContentResolver().insert(  
  288.                             Images.Media.EXTERNAL_CONTENT_URI, values);  
  289.   
  290.                 } catch (Exception e) {  
  291.                     e.printStackTrace();  
  292.                 }  
  293.   
  294.             }  
  295.         });  
  296.     }  
  297.   
  298.     private void flipCamera() {  
  299.         int id = (cameraId == CameraInfo.CAMERA_FACING_BACK ? CameraInfo.CAMERA_FACING_FRONT  
  300.                 : CameraInfo.CAMERA_FACING_BACK);  
  301.         if (!openCamera(id)) {  
  302.             alertCameraDialog();  
  303.         }  
  304.     }  
  305.   
  306.     private void alertCameraDialog() {  
  307.         AlertDialog.Builder dialog = createAlert(CameraDemoActivity.this,  
  308.                 "Camera info""error to open camera");  
  309.         dialog.setNegativeButton("OK"new DialogInterface.OnClickListener() {  
  310.             @Override  
  311.             public void onClick(DialogInterface dialog, int which) {  
  312.                 dialog.cancel();  
  313.   
  314.             }  
  315.         });  
  316.   
  317.         dialog.show();  
  318.     }  
  319.   
  320.     private Builder createAlert(Context context, String title, String message) {  
  321.   
  322.         AlertDialog.Builder dialog = new AlertDialog.Builder(  
  323.                 new ContextThemeWrapper(context,  
  324.                         android.R.style.Theme_Holo_Light_Dialog));  
  325.         dialog.setIcon(R.drawable.ic_launcher);  
  326.         if (title != null)  
  327.             dialog.setTitle(title);  
  328.         else  
  329.             dialog.setTitle("Information");  
  330.         dialog.setMessage(message);  
  331.         dialog.setCancelable(false);  
  332.         return dialog;  
  333.   
  334.     }  
  335.   
  336.     private void flashOnButton() {  
  337.         if (camera != null) {  
  338.             try {  
  339.                 Parameters param = camera.getParameters();  
  340.                 param.setFlashMode(!flashmode ? Parameters.FLASH_MODE_TORCH  
  341.                         : Parameters.FLASH_MODE_OFF);  
  342.                 camera.setParameters(param);  
  343.                 flashmode = !flashmode;  
  344.             } catch (Exception e) {  
  345.                 // TODO: handle exception  
  346.             }  
  347.   
  348.         }  
  349.     }  
  350. }  
Thanks for reading my article. If anyone has an issue or query about this code then provide it in the comments box.