Nowadays camera become one the major features that lot of apps provides. You can see the camera feature excessively used in apps in the area of food, social networking, video sharing apps. Integrating camera in your app is very simple task if you are not expecting a custom UI.

In this article we are going to see how to integrate the basic camera feature that takes pictures or record video through your app.

android-recyclerview-databinding-example

1. Android Camera API

There are two ways to integrate the camera module.

  • Using In-built Camera App:
  • The easiest way to integrate camera feature is, use the in-built camera app that comes with the device. To launch the camera app, you just need to pass the appropriate intent with necessary flags. Rest will be taken care by the camera app and it will return the data (image or video) to your app. The disadvantage of this method is, you can’t customize the camera interface as you would be launching third party camera app.

  • Writing Custom Camera App:
  • Building your own camera module takes some effort as you need to build everything from scratch beginning with user interface to integrating camera API (rending camera preview, toggling front and back cameras, flash, focus etc.,). But the advantage over here is, you can build the uniform camera UI which will be same for all the users. You can see custom camera in apps like Instagram, Facebook etc.,

Below is the demo app that we gonna build in this article. The UI is very minimal with two buttons and an area to preview the captured image or video.

android-camera-tutorial-capture-image-record-video

Now let’s start by creating a new project in Android Studio.

2. Creating New Project

1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from templates.

2. Open app/build.gradle and add Dexter dependency to request the runtime permissions.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    // ...

    // dexter runtime permissions
    implementation 'com.karumi:dexter:4.2.0'
}

3. Add the below resources to respective strings.xml, colors.xml and dimens.xml

<resources>
    <string name="app_name">Android Camera</string>
    <string name="action_settings">Settings</string>
    <string name="preview_description">Image and Video preview will appear here</string>
    <string name="btn_take_picture">Take Picture</string>
    <string name="btn_record_video">Record Video</string>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#1fb49c</color>
    <color name="colorPrimaryDark">#1fb49c</color>
    <color name="colorAccent">#FF4081</color>
</resources>
<resources>
    <dimen name="activity_margin">16dp</dimen>
    <dimen name="dimen_8">8dp</dimen>
</resources>

4. Under res, create a new folder named xml. Inside xml folder, create a new xml file name file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

5. Open AndroidManifest.xml and add CAMERA, WRITE_EXTERNAL_STORAGE and RECORD_AUDIO permissions.

Here we also added camera feature that defines the rules to list the app on Playstore. If we keep android:required=”true”, Google Playstore won’t let the users to install the app on the devices that doesn’t have camera feature. Incase of false, the app will be listed but camera feature is optional.

We also need <provider> tag to prepare the file paths properly across all the android platforms.

<uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.androidcamera">

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
    </application>
</manifest>

6. Create a class named CameraUtils.java and add the below methods. This is a helper class that provides necessary methods that we need in our camera module.

  • refreshGallery() – Refreshes the image gallery after taking a new picture or video so that they will be instantly available in the gallery. In older android devices, gallery won’t be refreshed until the device is rebooted.
  • checkPermissions() – Checks whether all the permissions are granted or not. This would be called before requesting the camera.
  • getOutputMediaFile() – Create a new file in gallery and returns the file. This reference will be passed to camera intent so that newly taken image / video will be stored in this location.
  • optimizeBitmap() – Compresses the bitmap before displaying it on UI to avoid the OutOfMemory exceptions.
package info.androidhive.androidcamera;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CameraUtils {

    /**
     * Refreshes gallery on adding new image/video. Gallery won't be refreshed
     * on older devices until device is rebooted
     */
    public static void refreshGallery(Context context, String filePath) {
        // ScanFile so it will be appeared on Gallery
        MediaScannerConnection.scanFile(context,
                new String[]{filePath}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                    }
                });
    }

    public static boolean checkPermissions(Context context) {
        return ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * Downsizing the bitmap to avoid OutOfMemory exceptions
     */
    public static Bitmap optimizeBitmap(int sampleSize, String filePath) {
        // bitmap factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = sampleSize;

        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * Checks whether device has camera or not. This method not necessary if
     * android:required="true" is used in manifest file
     */
    public static boolean isDeviceSupportCamera(Context context) {
        if (context.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }

    /**
     * Open device app settings to allow user to enable permissions
     */
    public static void openSettings(Context context) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts("package", BuildConfig.APPLICATION_ID, null));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static Uri getOutputMediaFileUri(Context context, File file) {
        return FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
    }

    /**
     * Creates and returns the image or video file before opening the camera
     */
    public static File getOutputMediaFile(int type) {

        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                MainActivity.GALLERY_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.e(MainActivity.GALLERY_DIRECTORY_NAME, "Oops! Failed create "
                        + MainActivity.GALLERY_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Preparing media file naming convention
        // adds timestamp
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MainActivity.MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + "." + MainActivity.IMAGE_EXTENSION);
        } else if (type == MainActivity.MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + "VID_" + timeStamp + "." + MainActivity.VIDEO_EXTENSION);
        } else {
            return null;
        }

        return mediaFile;
    }

}

7. Now open the layout files of main activity i.e activity_main.xml and content_main.xml and add the below layout code. Here we are defining couple of Buttons, ImageView and VideoView to preview the captured media.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="@dimen/activity_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="@dimen/activity_margin"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/txt_desc"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:padding="10dp"
            android:text="@string/preview_description"
            android:textSize="15dp" />

        <!-- To display picture taken -->
        <ImageView
            android:id="@+id/imgPreview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:visibility="gone" />

        <!-- To preview video recorded -->
        <VideoView
            android:id="@+id/videoPreview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:visibility="gone" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">

        <!-- Capture picture button -->
        <Button
            android:id="@+id/btnCapturePicture"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/dimen_8"
            android:layout_weight="1"
            android:background="@color/colorPrimary"
            android:foreground="?attr/selectableItemBackground"
            android:text="@string/btn_take_picture"
            android:textColor="@android:color/white" />

        <!-- Record video button -->
        <Button
            android:id="@+id/btnRecordVideo"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/dimen_8"
            android:layout_weight="1"
            android:background="@color/colorPrimary"
            android:foreground="?attr/selectableItemBackground"
            android:text="@string/btn_record_video"
            android:textColor="@android:color/white" />
    </LinearLayout>
</LinearLayout>

8. Finally open MainActivity.java and modify the code as shown below.

  • In onCreate(), the availability of the camera is checked using isDeviceSupportCamera() method and activity is closed if the camera is absent on the device.
  • On button click, checkPermissions() method is used the check whether required permissions are granted or not. If not granted, requestCameraPermission() method shows the permissions dialog to user.
  • captureImage() open the camera app to capture the image.
  • captureVideo() opens the camera app to record the video.
  • Once the media is captured, the image or video will be saved to gallery. previewCapturedImage() and previewVideo() renders the captured image / video on the screen.
  • showPermissionsAlert() – Shows an alert dialog propting user to enable the permissions in app settings incase they are denied permanently.
package info.androidhive.androidcamera;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.io.File;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // Activity request codes
    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;

    // key to store image path in savedInstance state
    public static final String KEY_IMAGE_STORAGE_PATH = "image_path";

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    // Bitmap sampling size
    public static final int BITMAP_SAMPLE_SIZE = 8;

    // Gallery directory name to store the images or videos
    public static final String GALLERY_DIRECTORY_NAME = "Hello Camera";

    // Image and Video file extensions
    public static final String IMAGE_EXTENSION = "jpg";
    public static final String VIDEO_EXTENSION = "mp4";

    private static String imageStoragePath;

    private TextView txtDescription;
    private ImageView imgPreview;
    private VideoView videoPreview;
    private Button btnCapturePicture, btnRecordVideo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Checking availability of the camera
        if (!CameraUtils.isDeviceSupportCamera(getApplicationContext())) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! Your device doesn't support camera",
                    Toast.LENGTH_LONG).show();
            // will close the app if the device doesn't have camera
            finish();
        }

        txtDescription = findViewById(R.id.txt_desc);
        imgPreview = findViewById(R.id.imgPreview);
        videoPreview = findViewById(R.id.videoPreview);
        btnCapturePicture = findViewById(R.id.btnCapturePicture);
        btnRecordVideo = findViewById(R.id.btnRecordVideo);

        /**
         * Capture image on button click
         */
        btnCapturePicture.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (CameraUtils.checkPermissions(getApplicationContext())) {
                    captureImage();
                } else {
                    requestCameraPermission(MEDIA_TYPE_IMAGE);
                }
            }
        });

        /**
         * Record video on button click
         */
        btnRecordVideo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (CameraUtils.checkPermissions(getApplicationContext())) {
                    captureVideo();
                } else {
                    requestCameraPermission(MEDIA_TYPE_VIDEO);
                }
            }
        });

        // restoring storage image path from saved instance state
        // otherwise the path will be null on device rotation
        restoreFromBundle(savedInstanceState);
    }

    /**
     * Restoring store image path from saved instance state
     */
    private void restoreFromBundle(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (savedInstanceState.containsKey(KEY_IMAGE_STORAGE_PATH)) {
                imageStoragePath = savedInstanceState.getString(KEY_IMAGE_STORAGE_PATH);
                if (!TextUtils.isEmpty(imageStoragePath)) {
                    if (imageStoragePath.substring(imageStoragePath.lastIndexOf(".")).equals("." + IMAGE_EXTENSION)) {
                        previewCapturedImage();
                    } else if (imageStoragePath.substring(imageStoragePath.lastIndexOf(".")).equals("." + VIDEO_EXTENSION)) {
                        previewVideo();
                    }
                }
            }
        }
    }

    /**
     * Requesting permissions using Dexter library
     */
    private void requestCameraPermission(final int type) {
        Dexter.withActivity(this)
                .withPermissions(Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        if (report.areAllPermissionsGranted()) {

                            if (type == MEDIA_TYPE_IMAGE) {
                                // capture picture
                                captureImage();
                            } else {
                                captureVideo();
                            }

                        } else if (report.isAnyPermissionPermanentlyDenied()) {
                            showPermissionsAlert();
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).check();
    }


    /**
     * Capturing Camera Image will launch camera app requested image capture
     */
    private void captureImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        File file = CameraUtils.getOutputMediaFile(MEDIA_TYPE_IMAGE);
        if (file != null) {
            imageStoragePath = file.getAbsolutePath();
        }

        Uri fileUri = CameraUtils.getOutputMediaFileUri(getApplicationContext(), file);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        // start the image capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
    }

    /**
     * Saving stored image path to saved instance state
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on screen orientation
        // changes
        outState.putString(KEY_IMAGE_STORAGE_PATH, imageStoragePath);
    }

    /**
     * Restoring image path from saved instance state
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        imageStoragePath = savedInstanceState.getString(KEY_IMAGE_STORAGE_PATH);
    }

    /**
     * Launching camera app to record video
     */
    private void captureVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

        File file = CameraUtils.getOutputMediaFile(MEDIA_TYPE_VIDEO);
        if (file != null) {
            imageStoragePath = file.getAbsolutePath();
        }

        Uri fileUri = CameraUtils.getOutputMediaFileUri(getApplicationContext(), file);

        // set video quality
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file

        // start the video capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
    }

    /**
     * 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) {
                // Refreshing the gallery
                CameraUtils.refreshGallery(getApplicationContext(), imageStoragePath);

                // 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) {
                // Refreshing the gallery
                CameraUtils.refreshGallery(getApplicationContext(), imageStoragePath);

                // 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 gallery
     */
    private void previewCapturedImage() {
        try {
            // hide video preview
            txtDescription.setVisibility(View.GONE);
            videoPreview.setVisibility(View.GONE);

            imgPreview.setVisibility(View.VISIBLE);

            Bitmap bitmap = CameraUtils.optimizeBitmap(BITMAP_SAMPLE_SIZE, imageStoragePath);

            imgPreview.setImageBitmap(bitmap);

        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    /**
     * Displaying video in VideoView
     */
    private void previewVideo() {
        try {
            // hide image preview
            txtDescription.setVisibility(View.GONE);
            imgPreview.setVisibility(View.GONE);

            videoPreview.setVisibility(View.VISIBLE);
            videoPreview.setVideoPath(imageStoragePath);
            // start playing
            videoPreview.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Alert dialog to navigate to app settings
     * to enable necessary permissions
     */
    private void showPermissionsAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Permissions required!")
                .setMessage("Camera needs few permissions to work properly. Grant them in settings.")
                .setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        CameraUtils.openSettings(MainActivity.this);
                    }
                })
                .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
    }
}

Run and test the app on a real device. You can see the app working as shown in the demo screenshots.

Subscribe
Notify of
guest
199 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Sukumar
Sukumar
7 years ago

Nice Example

Raj Amal
7 years ago

Nice tutorial

Jeffy Lazar
Jeffy Lazar
7 years ago

Thank you so much …thank you so much …..thanks a lot man …you are the best 🙂 🙂

Ravi Tamada
7 years ago
Reply to  Jeffy Lazar

You are welcome:)

Sagar Maiyad
Sagar Maiyad
7 years ago

Sorry, but you are not using any Camera API.. its buitin camera..

Ravi Tamada
7 years ago
Reply to  Sagar Maiyad

I’ll change the title

Sagar Maiyad
Sagar Maiyad
7 years ago
Reply to  Ravi Tamada

Okey, but can you tell me, is it working in all devices or not.??

Ajay Patel
Ajay Patel
7 years ago

Your site now looks like songs.pk, its quality is not same as previous one. Like songs.pk your site full of adverts. It really sucks 🙁

Ravi Tamada
7 years ago
Reply to  Ajay Patel

I need some money to maintain site right ?

suncap
suncap
7 years ago
Reply to  Ravi Tamada

I will click on all your adverts

Ravi Tamada
7 years ago
Reply to  suncap

Hi Suncap, Thanks for the help. But if we click ads intentionally my ads account will be cancelled 🙂

Connery Sean
Connery Sean
7 years ago
Reply to  Ravi Tamada

Hey I like your site !
Keep up the good work

Jeffy Lazar
Jeffy Lazar
7 years ago
Reply to  Connery Sean

ads are not of any problem …we dont even notice the ads as long as you keep posting such amazing and yet so easy to understand Android Tutorials.

Keep up the great work 🙂 🙂

Krunal Doshi
Krunal Doshi
7 years ago
Reply to  Ravi Tamada

Start Premium Tutorial that only Premium users can access.

maulik
maulik
7 years ago
Reply to  Ravi Tamada

we all are eagerly waiting for the Design and Tips section!

Ravi Tamada
7 years ago
Reply to  maulik

Yeah, they are under construction…

Steffy
Steffy
7 years ago
Reply to  Ravi Tamada

Sir do you use any cms ?

suncap
suncap
7 years ago
Reply to  Ravi Tamada

AdsBlock+ FTW !!! 😛

Sagar Maiyad
Sagar Maiyad
7 years ago

Have you any Example related to Camera API..?? if, then please publish here.. it will very useful for all and specialy for me.

Jumman
Jumman
7 years ago

How can I crop from camera preview with bounding box for selecting the region before capturing the images? like “Translanguage OCR” (https://play.google.com/store/apps/details?id=com.translanguage.free.version&hl=en) ,please help me regarding this .thanks

Lakshmi Reddy Kanneti
Lakshmi Reddy Kanneti
7 years ago

sir you r mention fileurl in path.where is the image are video store.i want to store a capture images are videos in remote server.how can i do that. i am new for android .give me a start up .and also i am using that images and videos to send a message like whatapp.

Connery Sean
Connery Sean
7 years ago

My guess would be that you have to store your Images on your mobile first, and than push them online using some other technology to comunicate with your web server

Ravi Tamada
7 years ago
Reply to  Connery Sean

Correct!

koko landry
koko landry
7 years ago
Reply to  Ravi Tamada

what are those technologies that I can use to get my picture on a remote server? i really need this for my project. can u please help?

Steffy
Steffy
7 years ago

Nice tutorial ! Sir do you use any CMS for this website ? Its awesome !

Ravi Tamada
7 years ago
Reply to  Steffy

Yeah WordPress

sakthivel
sakthivel
7 years ago

thanks good tutorial. my small request make it android seekbar for value increment and decrement tutorial.
best thanks
sakthivel

sdfgh
sdfgh
4 years ago
Reply to  sakthivel

hhhhhh

Tulai Paul
Tulai Paul
7 years ago

Such articles may prompt the mobile ad network companies and their apps and games developers to provide apps and games that are based on live camera. The list of such companies have been increasing constantly like admob, revmob, chartboost, tapjoy, adcolony, appnext, inmobi and so on

Joey
Joey
7 years ago

Great tutorial man! Thnx! But do you know why my images show up with the default file names? The code renames video files, that’s good! Also, i can’t move the images to a custom folder? Hope you can help me!

mangesh kaduskar
mangesh kaduskar
7 years ago

I took video from camera but now i want to upload it to YouTube. Will you please give me tutorial of how to upload video to YouTube.

Pablo
Pablo
7 years ago

Ravi I am getting an error:
Pictures work just fine, but when I try to record video, the camera is launched but when I stop recording the app crashes, any ideas? I am running it on a 2.3.6 android version.

Shri Kant
Shri Kant
7 years ago
Reply to  Pablo

same problem here.

dhnjy 18
dhnjy 18
7 years ago
Reply to  Shri Kant

Am also facing the same problem. did you find any solution. plz tell me

Douglas Roos
Douglas Roos
7 years ago

How can i change the resolution and quality of the photo because when i send the photo to my webserver takes a long time, the photos have a size of 2mb or more.

Hari Haran Ayyappan
Hari Haran Ayyappan
7 years ago
Reply to  Douglas Roos

Hi Roos , In what format you are sending the pics to server

Douglas Roos
Douglas Roos
7 years ago

Hi Hari, i’m sending the photos in JPG format through MultiPartEntityBuilder, i’ve solved the problem downsampling the photo from the bitmap, rewriting the original photo and sending it to the server.

Hari Haran Ayyappan
Hari Haran Ayyappan
7 years ago
Reply to  Douglas Roos

MultiPartEntity means are you using apache http multi entity jars? I am decompressing bitmap and sending .when i am decompressing , and subimtting to server i am getting out of memory exception. Did you experience this issue

Ugur Cakmak
Ugur Cakmak
7 years ago

I’m triggering image capture intent from a custom dialogs button. After I succesfully saving the image to sdcard, application restarts and my dialog dissappears. I don’t want to restart my application, it’s not I want. I simply want after capture, return to where I was. How can I do that ?

Uğur Çakmak
Uğur Çakmak
7 years ago
Reply to  Ugur Cakmak

I commented out InstanceState Methods and now I’m fine. but in order to save my images in portrait mode, I should take a picture in landscape mode. I want to save images in proper modes like portrait in portrait, you know the rest. any suggestions ?

Gilbert
Gilbert
7 years ago

Great tutorial man

jj
jj
7 years ago

this tutorial isn’t on the custom camera i found a better one here http://appskort.com/android-camera-tutorial

Ravi Kant chauhan
Ravi Kant chauhan
7 years ago
Reply to  jj

brother can u send me complete code with directory structure for only camera activity..that means i want to take a pic and want to upload to the server..pls brother send me

ravikantchauhan009@gmail.com

Carlos
Carlos
7 years ago
Reply to  jj

it doesn´t work in Tablet Nexus 7, because it has no SD card !!

Carlos
Carlos
7 years ago
Reply to  Carlos

Your app works amazing in my Nexus 7 – 2013 !!, thanks Ravi

Ankita Patel
Ankita Patel
7 years ago

sir how to integrate this camera code in to all type of barcode reader in android

Stefan
Stefan
7 years ago

Whenever I start the app there is a black background until I click the button… Afterwards it’s working just fine… Does anyone know this problem?

Poojan Sharma
Poojan Sharma
7 years ago

Hi Ravi,
I’m having some problem, i’ve implemented your code into my app but i’m confused as to how to store the captured image into my local storage. Please help me on this.

gautam behera
gautam behera
7 years ago

Hello,
I ran your code but I am not able to get a portrait image. When I take an image in portrait it becomes landscape in the app.
So is it possible to get a portrait image.

Dhruvit Darji
Dhruvit Darji
6 years ago
Reply to  gautam behera

that is the bug which is already reported in android community and still they are working to fix it.. some people suggest to use EXIF techniques but be frank then it is not working in most of devices it always returning 0 rotation… if you have found any solution then plz let me know.. i badly require that…

Derdus
Derdus
7 years ago

Your code works perfectly well, but i am not able to capture the video capture. Help me please

Tyler
Tyler
7 years ago

Hello, my phone does not have a sd card(at least no sd card slot) so where would it be storing my pictures when I take them?

Thank you,
Tyler

Jekyll Bermeo
Jekyll Bermeo
7 years ago

Hello how will i fetch the captured image path?

koko landry
koko landry
7 years ago

nice tutorial. how do i upload pictures/videos to a remote server ? this will be of much help. tx

Andre Piper
Andre Piper
7 years ago

How do I set the recording limit, I didn’t see that in the code.

Kinjal Patel
Kinjal Patel
7 years ago

how we tak more than one shots programatically for android custom camera?

emiliano
emiliano
7 years ago

Hi, how can i adapt this code to use inside fragment? Thanks.-

Muaaz Odabashi
Muaaz Odabashi
7 years ago
Reply to  emiliano

any luck?

Mona Elgnedy
Mona Elgnedy
7 years ago

Plz , If I want camera hidden and silent ?? how

Sinan
Sinan
7 years ago

How can I save the captured image on a server (localhost) instead of the sd-card?

Walter Reyes
Walter Reyes
7 years ago
Reply to  Sinan

You would also need to make an api to handle the http calls. This is not too difficult with php and slim framework

Sinan
Sinan
7 years ago
Reply to  Walter Reyes

Hi Walter,
Thanks for your answer. But are you able to provide me some helpful links or tutorials ?

Gabriel Galang
Gabriel Galang
7 years ago

how could i save this on database sqlite???

and anytutorial for camera to blob then to sqlite / sqlite to imageview 😀

golla priyanka
golla priyanka
5 years ago
Reply to  Gabriel Galang

hie if u got the answer please explain me

Ravi Tamada
5 years ago
Reply to  golla priyanka

Why do you want to store the image in SQlite?

Paradisos
Paradisos
7 years ago

Can please someone tell me what the “Activity request codes” is and why do I have to add a number ?
I don’t see any use after….

s.shivasurya
6 years ago
Reply to  Paradisos

may be since it is accessing camera API it may be response code like HTTP respnse
i guessed answer with http response
pls go through the Camera API in docs!

Carlos
Carlos
7 years ago

Excellent tutorial Ravi, congratulations. Please, let me do it a question. How could I add effect image to you camera?, for example color gray, sepia toning in Android NDK C++/C?.
Regards,
Carlos

Carla
Carla
7 years ago

my videos and photos are not saved, do I have to adjust some code?

jason
jason
7 years ago

Hi thx for this great tuto. Plz how can we store the captured photo or video directly on mysql database and how can we resize the picture before storage !!!!

ubro
ubro
7 years ago
Reply to  jason

Any answer Ravi plz for this question ???

Jasson Faerron
Jasson Faerron
6 years ago
Reply to  jason

i think you need to use Bitmap and create a byte[] from Bitmap and then create the statement to store

s.shivasurya
6 years ago

nice tutorial :disqus sir! easy to understand!

SIR NAME İS MAHO
SIR NAME İS MAHO
6 years ago
Reply to  s.shivasurya

SİİİR.. SİİİR RAVİİİİ.. SİR.. IIIH .. IMMMM SIRR

Join Kelly
Join Kelly
6 years ago

Why not support nexus 7 device ?

Nagginda Sumayyia
Nagginda Sumayyia
6 years ago

May anyone help me please. i want to know how to submit both the image and the video captured from android device to mysql/PHP database.

Huỳnh Thanh Tuấn
Huỳnh Thanh Tuấn
6 years ago

someone help me…how to call intent into ArrayAdapter…i have one gridview and once gridview_item have a image…i want when click into this image,it will call intent give them take a picture

Laureen Tan
Laureen Tan
6 years ago

Thank you for the tutorial. But anyone know how I can retrieve all the images that is saved in folder after following the steps above from my phone?

Absar Hussain
Absar Hussain
6 years ago

i copy paste that code .. no errors .. But this code is not working.. can anyone help me??

youming2007
youming2007
6 years ago

There are some code errors in this tutorial: (It takes me 2 hours to get around with them xD)

1. When recording video, it will throw error after recording and saving recorded video to the location specified in MediaStore.EXTRA_OUTPUT, as mentioned here: http://stackoverflow.com/questions/12458318/nullpointerexception-at-com-sec-android-app-camera-camcorderengine-renametempfil. Solution is just remove that line and assign a value to fileUri = data.getData() in onActivityResult callback. The recorded video would be save in default location.

2. Use videoPreview.setVideoURI(fileUri) instead of videoPreview.setVideoPath(fileUri.getPath) when working with the above workaround because data.getData() return a uri related to a media content provider instead of actual path.

Anyway, it’s an awesome tutorial.

sanjay
sanjay
4 years ago
Reply to  youming2007

Thanks, same error i was also getting while saving the video file.

ah_trini
ah_trini
6 years ago

good tutorial :)!

It will also threw errors for the overidden “SetOnClickListener”methods for the buttons.

Remove those two methods and add these for the respective button tagsin xml.
android:onClick=”captureImage”

android:onClick=”recordVideo”

ah_trini
ah_trini
6 years ago
Reply to  ah_trini

oh and change the method signatures to:
public void captureImage(View view){}
public void recordVideo(View view){}

sania12
sania12
6 years ago

it s working fine but it s taking such a long time after capturing image

Naman Gupta
Naman Gupta
6 years ago

Hey! The preview is not working in the app. The Image gets stored in the right directory, but after the camera closes, their is nothing to display on the app activity.

Damian Dennis
Damian Dennis
6 years ago

nice one, best tutorial so far.

yamuna
yamuna
6 years ago

i import your source code but my application displaying force to close message

yamuna
yamuna
6 years ago

when i click take the photo button it waits 2sec and displays force to close an application message

mukesh
mukesh
6 years ago

Hey! can we do same for front facing camera ?

199
0
Would love your thoughts, please comment.x
()
x