Home > DeveloperSection > Articles > Camera API in Android

Camera API in Android


Android Android  API(s) 
Ratings:
0 Comment(s)
 602  View(s)
Rate this:

Camera API in Android


The Android framework includes support for various cameras and camera features available on devices, allowing you to capture pictures and videos in your applications. This article discusses a quick, simple approach to image and video capture and outlines an advanced approach for creating custom camera experiences for your users.

The Camera class is used to set image capture settings, start/stop preview, snap pictures, and retrieve frames for encoding for video. This class is a client for the Camera service, which manages the actual camera hardware.

First of all you have need to permission for using camera in your application. Show you must be add permission in AndroidManifest.xml file

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

Here I am creating a sample for capturing image and capturing video via using camera in your device.

1.      Create an Android project

2.      Add views in activity_main.xml file

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="horizontal"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity" >

 

    <LinearLayout

        android:layout_width="0dp"

        android:layout_height="wrap_content"

        android:layout_gravity="center"

        android:layout_weight=".40"

        android:orientation="vertical" >

 

        <Button

            android:id="@+id/btnCapImage"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="Capture Image" />

 

        <Button

            android:id="@+id/btnCapVideo"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_marginTop="5sp"

            android:text="Capture Video" />

    </LinearLayout>

 

    <LinearLayout

        android:layout_width="0sp"

        android:layout_height="fill_parent"

        android:layout_weight=".60"

        android:background="@drawable/customborder"

        android:orientation="vertical" >

 

        <TextView

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:gravity="center"

            android:text="preview" />

 

        <ImageView

            android:id="@+id/myImage"

            android:layout_width="fill_parent"

            android:layout_height="fill_parent"

            android:visibility="gone" />

 

        <VideoView

            android:id="@+id/myVideo"

            android:layout_width="fill_parent"

            android:layout_height="450dp"

            android:visibility="gone" />

    </LinearLayout>

 

</LinearLayout>

 

3.       My AndroidManifest.xml file

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.androidcamera"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="18" />

 

    <uses-feature android:name="android.hardware.camera" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-permission android:name="android.permission.RECORD_AUDIO" />

 

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name="com.example.androidcamera.MainActivity"

            android:label="@string/app_name"

            android:screenOrientation="landscape" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

            <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

 

</manifest>

4.      Add following code in MainActivity.class

package com.example.androidcamera;

import java.io.File;

public class MainActivity extends Activity {

                // Activity request codes

                private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;

                private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;

                public static final int MEDIA_TYPE_IMAGE = 1;

                public static final int MEDIA_TYPE_VIDEO = 2;

                // directory name to store captured images and videos

                private static final String IMAGE_DIRECTORY_NAME = "Hello Camera"; 

                private Uri fileUri; // file url to store image/video

                private ImageView imgPreview;

                private VideoView videoPreview;

                private Button btnCapturePicture, btnRecordVideo; 

                @Override

                protected void onCreate(Bundle savedInstanceState) {

                                super.onCreate(savedInstanceState);

                                setContentView(R.layout.activity_main);

                                imgPreview = (ImageView) findViewById(R.id.myImage);

                                videoPreview = (VideoView) findViewById(R.id.myVideo);

                                btnCapturePicture = (Button) findViewById(R.id.btnCapImage);

                                btnRecordVideo = (Button) findViewById(R.id.btnCapVideo);                   

                                 // Capture image button click event                      

                                btnCapturePicture.setOnClickListener(new View.OnClickListener() { 

                                                @Override

                                                public void onClick(View v) {

                                                                // capture picture

                                                                captureImage();

                                                }

                                });          

                                 // Record video button click event                         

                                btnRecordVideo.setOnClickListener(new View.OnClickListener() { 

                                                @Override

                                                public void onClick(View v) {

                                                                // record video

                                                                recordVideo();

                                                }

                                });

                                // checking camera availability

                                if (!isDeviceSupportCamera()) {

                                                Toast.makeText(getApplicationContext(),

                                                                                "Sorry! Your device doesn't support camera",

                                                                                Toast.LENGTH_LONG).show();

                                                // will close the app if the device does't have camera

                                                finish();

                                }

                }               

                 // Checking device has camera hardware or not              

                private boolean isDeviceSupportCamera() {

                                if (getApplicationContext().getPackageManager().hasSystemFeature(

                                                                PackageManager.FEATURE_CAMERA)) {

                                                // this device has a camera

                                                return true;

                                } else {

                                                // no camera on this device

                                                return false;

                                }

                }             

                 //Capturing Camera Image will launch camera app requrest image capture         

                private void captureImage() {

                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 

                                fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

                                intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

                                // start the image capture Intent

                                startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

                }

                // Here we store the file url as it will be null after returning from camera app     

                @Override

                protected void onSaveInstanceState(Bundle outState) {

                                super.onSaveInstanceState(outState);

                                // save file url in bundle as it will be null on scren orientation changes

                                outState.putParcelable("file_uri", fileUri);

                } 

                @Override

                protected void onRestoreInstanceState(Bundle savedInstanceState) {

                                super.onRestoreInstanceState(savedInstanceState); 

                                // get the file url

                                fileUri = savedInstanceState.getParcelable("file_uri");

                }             

                // Recording video         

                private void recordVideo() {

                                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); 

                                fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);

                                // set video quality

                                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

                                intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

                           // set the image file name

                // start the video capture Intent

                                startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);

                }              

                 // Receiving activity result method will be called after closing the camera                 

                @Override

                protected void onActivityResult(int requestCode, int resultCode, Intent data) {

                                // if the result is capturing Image

                                if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {

                                                if (resultCode == RESULT_OK) {

                                                                // successfully captured the image

                                                                // display it in image view

                                                                previewCapturedImage();

                                                } else if (resultCode == RESULT_CANCELED) {

                                                                // user cancelled Image capture

                                                                Toast.makeText(getApplicationContext(),

                                                                  "User cancelled image capture", Toast.LENGTH_SHORT) .show();

                                                } else {

                                                                // failed to capture image

                                                                Toast.makeText(getApplicationContext(),

                                            "Sorry! Failed to capture image", Toast.LENGTH_SHORT) .show();

                                                }

                                } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {

                                                if (resultCode == RESULT_OK) {

                                                                // video successfully recorded

                                                                // preview the recorded video

                                                                previewVideo();

                                                } else if (resultCode == RESULT_CANCELED) {

                                                                // user cancelled recording

                                                                Toast.makeText(getApplicationContext(),

                                  "User cancelled video recording", Toast.LENGTH_SHORT) .show();

                                                } else {

                                                                // failed to record video

                                                                Toast.makeText(getApplicationContext(),

                                              "Sorry! Failed to record video", Toast.LENGTH_SHORT) .show();

                                                }

                                }

                }             

                 //Display image from a path to ImageView        

                private void previewCapturedImage() {

                                try {

                                                // hide video preview

                                                videoPreview.setVisibility(View.GONE);

                                                imgPreview.setVisibility(View.VISIBLE);

                                                // bimatp factory

                                                BitmapFactory.Options options = new BitmapFactory.Options();

                                                // downsizing image as it throws OutOfMemory Exception for larger

                                                // images

                                                options.inSampleSize = 8;

                                                final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),

                                                                                options);

                                                imgPreview.setImageBitmap(bitmap);

                                } catch (NullPointerException e) {

                                                e.printStackTrace();

                                }

                }            

                 // Previewing recorded video                 

                private void previewVideo() {

                                try {

                                                // hide image preview

                                                imgPreview.setVisibility(View.GONE);

                                                videoPreview.setVisibility(View.VISIBLE);

                                                videoPreview.setVideoPath(fileUri.getPath());

                                                // start playing

                                                videoPreview.start();

                                } catch (Exception e) {

                                                e.printStackTrace();

                                }

                }               

                // creating file uri to store image/video                 

                public Uri getOutputMediaFileUri(int type) {

                                return Uri.fromFile(getOutputMediaFile(type));

                }             

                // returning image / video          

                private static File getOutputMediaFile(int type) { 

                                // External sdcard location

                                File mediaStorageDir = new File(

                                                             Environment  .getExternalStoragePublicDirectory(Environment. DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME); 

                                // Create the storage directory if it does not exist

                                if (!mediaStorageDir.exists()) {

                                                if (!mediaStorageDir.mkdirs()) {

                                                                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "

                                                                                                + IMAGE_DIRECTORY_NAME + " directory");

                                                                return null;

                                                }

                                } 

                                // create a media file name

                                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",

                                                                Locale.getDefault()).format(new Date());

                                File mediaFile;

                                if (type == MEDIA_TYPE_IMAGE) {

                                                mediaFile = new File(mediaStorageDir.getPath() + File.separator

                                                                                + "IMG_" + timeStamp + ".jpg");

                                } else if (type == MEDIA_TYPE_VIDEO) {

                                                mediaFile = new File(mediaStorageDir.getPath() + File.separator

                                                                                + "VID_" + timeStamp + ".mp4");

                                } else {

                                                return null;

                                } 

                                return mediaFile;

                }

}

5.       Add shape for custom background as name customborder and paste following code.

 

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

 <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">

   <corners android:radius="20dp"/>

   <padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>

   <solid android:color="#CCCCCC"/>

 </shape>

   

Now run your application

  


Don't want to miss updates? Please click the below button!

Follow MindStick