Opening Camera In Android Studio Examples

Camera in android studio is used to take pictures and record videos. In this tutorial we will learn how to open camera or take pictures from gallery.

camera in android
Camera in Android

We will open both cameras front and back. We will take pictures and will store the image file into File object. Also we will show the image taken from the camera using android studio.

Camera is used to take pictures and record videos. It can be either front camera or back camera in android devices. We can also switch the camera from front to back or back to front during capturing images.

Add Permission To Use Camera in Android Studio

First we need to add some camera permissions in Manifest.java file. Add below camera permission:

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

Image Crope in Android Studio

After picking the Image from gallery of taken from camera We will send the image to crope. For this add the following dependency into build.gradle file –

//image croper
 api 'com.theartofdev.edmodo:android-image-cropper:2.8.+'

Add Cropper Class in The Manifest File

Add the following code into the Manifest file wrapping by Activity like below.

 <activity
    android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
    android:theme="@style/Base.Theme.AppCompat" />

Glide Dependency In Android Studio

Using the glide dependency it become easy to set the Image to the ImageView in android studio. Add the glide dependency in build.gradle file.

 implementation 'com.google.code.gson:gson:2.8.2'
 implementation 'com.github.bumptech.glide:glide:4.11.0'

Enable DataBinding in Android Studio

Please note that I used DataBinding in this project of example. You should enable databinding in android studio. Databinding is the way of reducing code length. If you want to learn how to enable databinding in android studio, click here.

Complete Example of Camera In Android Studio

Create following class and layout file in your project. You can directly copy and paste the following code into your projects.

layout file ( xml )

In the layout file I created a simple button to open the camera. Below the button I taken an ImageView to show the Image after clicked through camera or from local storage.

 <?xml version="1.0" encoding="utf-8"?>
 <layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        tools:context=".Fragment.AboutUsFragment">

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_gravity="center"
            android:text="Camera Example"
            android:textColor="@color/material_on_background_emphasis_medium"
            android:textSize="24dp" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Take Photo"
            android:textSize="16sp"
            android:padding="20dp"
            android:layout_centerInParent="true"
            android:layout_below="@id/text"/>

        <ImageView
            android:id="@+id/image"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:layout_centerInParent="true"
            android:layout_below="@id/button"/>

    </RelativeLayout>
 </layout>

Reading Camera Permission In Android Studio

Add following code in your Main class before onCreate() method. It will read the permission if already have then no action other wise it will ask to take camera permission in android.

  //permissions-------------------------------------------------------------
 private static String[] PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE,        android.Manifest.permission.READ_EXTERNAL_STORAGE, 
        Manifest.permission.CAMERA, };

 protected void makeRequest() {
    ActivityCompat.requestPermissions(getActivity(),
            new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,     Manifest.permission.CAMERA,},
            101);
 }

 public static boolean hasPermissions(Context context, String... permissions) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
 }

Put the following code below the onCreate() method to run the method when the activity open.

Complete Class For Camera Example

 package com.example.androidtestingproject.Activity;
 import androidx.appcompat.app.AppCompatActivity;
 import androidx.core.app.ActivityCompat;
 import androidx.databinding.DataBindingUtil;

 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.net.Uri;
 import android.os.Build;
 import android.os.Bundle;
 import android.os.Environment;
 import android.os.FileUtils;
 import android.view.View;

 import com.example.androidtestingproject.R;
 import com.example.androidtestingproject.databinding.ActivityDemoBinding;
 import com.theartofdev.edmodo.cropper.CropImage;
 import com.theartofdev.edmodo.cropper.CropImageView;

 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;

 public class DemoActivity extends AppCompatActivity {
    private ActivityDemoBinding binding;


    private static int PICK_IMAGE_REQUEST_CODE ;
    private File profilePath;

    //permissions-------------------------------------------------------------
    private static String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE,  Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA, };

    protected void makeRequest() {
        ActivityCompat.requestPermissions(this,
                new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE,  Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA,},
                101);
    }

    public static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }
    //


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_demo);

        if (!hasPermissions(this, PERMISSIONS)) {
            makeRequest();
        }

        initView();
    }

    private void initView() {

        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PICK_IMAGE_REQUEST_CODE = 1;
                CropImage.activity()
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .start(DemoActivity.this);
            }
        });
    }


    //onactivity
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                if (PICK_IMAGE_REQUEST_CODE == 1) {
                    Uri resultUri = result.getUri();
                    String imagePath = FileUtils.getPath(DemoActivity.this, resultUri);
                    Bitmap myBitmap = BitmapFactory.decodeFile(imagePath);
                    Bitmap converetdImage = getResizedBitmap(myBitmap, 300);
                    try {
                        profilePath = savebitmap(converetdImage);
                        binding.image.setImageBitmap(BitmapFactory.decodeFile(String.valueOf(profilePath)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
        }
    }
    //method
    public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();

        float bitmapRatio = (float)width / (float) height;
        if (bitmapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }

        return Bitmap.createScaledBitmap(image, width, height, true);
    }
    //method
    public File savebitmap(Bitmap bmp) throws IOException {
        File file = new File(Environment.getExternalStorageDirectory().getPath(), "MI/images");
        if (!file.exists()) {
            file.mkdirs();
        }
        File newFile = new File((file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg"));
        newFile.createNewFile();
        FileOutputStream fo = new FileOutputStream(newFile);
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fo);
        fo.close();
        return newFile;
    }
    //---------------------------------------

 }

Thank You for reading this tutorial. Please comment for your queries. Hope this tutorial helped you. You can visit more useful Tutorials for improving your development skills.

close

Don’t miss new tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment