Capturing Images


Interfacing camera is an important element in Android app. It enables you to capture images or record videos out of the Phone's camera unit.

Capturing an image from phones camera is very simple task and can be done as per code given below


Project Overview:


First we need to declare Camera Permission in Manifest File.

AndroidManifest.sml:


xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ourcoaching.simpleimagecapture">

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

<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

manifest>


However for API version>16, Camera permission needs to be taken in runtime

MainActivity.java:

package com.ourcoaching.simpleimagecapture;


import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.FileNotFoundException;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

private Button CAMERA, GALLERY;
private ImageView imageView;
private Bitmap bitmap;
private boolean hasCamera = false, hasPermission = false;

// any fixed number
private final int CAMERAPERMISSION = 432;

// assigning request variables
private final int Capture_Camera = 221, Capture_Gallery = 634;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

CAMERA = (Button) findViewById(R.id.button);
GALLERY = (Button) findViewById(R.id.button2);
imageView = (ImageView) findViewById(R.id.imageView);


// checking whether device has a camera hardware or not
hasCamera = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);

// checking for camera permissin and then requesting it if no permission granted

if (hasCamera) {
/* checking build version
android documentation says if build>KITKAT, then camera permission should be asked in runtime
else camera permission is given by default
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
hasPermission = true;
} else {
RequestCameraSystemPermissions();
}
} else {
hasPermission = true;
}
}
}


@Override
protected void onResume() {
super.onResume();

GALLERY.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CaptureGalleryImage();
}
});

CAMERA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CaptureCameraImage();
}
});
}

private void CaptureCameraImage() {
if (hasCamera) {
if (hasPermission) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, Capture_Camera);
} else {
Toast.makeText(this, "requesting permission", Toast.LENGTH_SHORT).show();
RequestCameraSystemPermissions();
}
} else {
Toast.makeText(this, "no camera present", Toast.LENGTH_SHORT).show();
}
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Capture_Camera) {
Bundle bundle = data.getExtras();
if (resultCode == RESULT_OK) {
bitmap = (Bitmap) bundle.get("data");
} else Toast.makeText(this, "failure 1", Toast.LENGTH_SHORT).show();
} else if (requestCode == Capture_Gallery) {
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

} else Toast.makeText(this, "failure 2", Toast.LENGTH_SHORT).show();
} else Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();


if (bitmap == null) {
Toast.makeText(this, "bitmap = null", Toast.LENGTH_SHORT).show();
} else {
imageView.setImageBitmap(bitmap);
}
}

private void CaptureGalleryImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, Capture_Gallery);
}

private void RequestCameraSystemPermissions() {
if (ContextCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.CAMERA)) {

// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.

} else {

// No explanation needed, we can request the permission.

ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.CAMERA},
CAMERAPERMISSION);

// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

switch (requestCode) {
case CAMERAPERMISSION:

if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted, yay! Do the
// contacts-related task you need to do.
hasPermission = true;
Toast.makeText(this, "Camera Permission Granted", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Camera Permission denied", Toast.LENGTH_LONG).show();
hasPermission = false;
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}


Layout files

activity_main.xml:

xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="com.ourcoaching.simpleimagecapture.MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CAMERA"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.855"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.879" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GALLERY"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.22"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.879" />

<ImageView
android:id="@+id/imageView"
android:layout_width="243dp"
android:layout_height="239dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.504"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.113"
app:srcCompat="@mipmap/ic_launcher" />
android.support.constraint.ConstraintLayout
>


UI layout looks like:



Download the project code from GITHUB



Related Tutorials