How to crop Image from Camera and Gallery in Android?

In this tutorial, we'll learn how to crop photos in the Android Gallery and Camera. There is no crop feature in this project, contrary to what was covered in the last post on how to choose an image from an Android gallery. When we snap pictures with our phones, we occasionally wish to change our profile pictures to reflect those images. The background must be eliminated, though. In that situation, we can post that image after removing the backdrop using the crop image option. Below is a sample video that will give you an idea of what this post will cover. Keep in mind that the Java programming language will be used to carry out this project.

Step by Step Execution

Step 1: Establish a New Project

Create a new project in Android Studio by selecting an Empty Activity.

Step 2: To the build.gradle ( Module:app ) file, add a dependency

To add the following dependency, go to Gradle Scripts >build.gradle(Module:app) and add it there.

// This library is utilised for the crop function in images.
api ‘com.theartofdev.edmodo:android-image-cropper:2.8.+’
// The cropped image is loaded into
// ImageView using this library.
implementation ‘com.squareup.picasso:picasso:2.5.2’

Step 3: AndroidManifest.xml file manipulation

To the AndroidManifest.xml file, add the following 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”/>

Insert the lines below within the <application> tag.

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

XML Code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	Package="com.anni.cropimage">
	<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" />
	<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>
		<activity			
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
			android:theme="@style/Base.Theme.AppCompat" />
	</application>
</manifest>

Step 4: Using the file activity main.xml

To add the following code to activity main.xml, go to the app > res > layout > activity main.xml. The code for the activity main.xml file is shown below.

XML Code:

<?xml version="1.0" encoding="utf-8"?>
<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:layout_marginBottom="100dp"
	android:gravity="center"
	android:orientation="vertical"
	tools:context=".MainActivity">


	<!--The chosen cropped image will be displayed here-->
	<ImageView
		android:id="@+id/set_profile_image"
		android:layout_width="300dp"
		android:layout_height="300dp"
		android:layout_alignParentTop="true"
		android:layout_centerHorizontal="true"
		android:layout_marginTop="40dp"
		android:src="@drawable/ic_image_black_24dp" />
	
	<!--Clicking on this phrase will allow us to choose 
an image from the camera or gallery -->
	<TextView
		android:id="@+id/click"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Pick an image by clicking here "
		android:textSize="22sp"
		android:textStyle="bold" />
</LinearLayout>

Step 5: Accessing and using the MainActivity.java file

Refer to the following code in MainActivity.java by visiting the file. The MainActivity.java file's source code is displayed below. To aid the reader in understanding the code, comments have been inserted inside the code.

Java Code:

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;


import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;


public class MainActivity extends AppCompatActivity {
	ImageViewuserpic;
	private static final int GalleryPick = 1;
private static final int CAMERA_REQUEST = 100;
	private static final int STORAGE_REQUEST = 200;
	private static final int IMAGEPICK_GALLERY_REQUEST = 300;
	private static final int IMAGE_PICKCAMERA_REQUEST = 400;
	String cameraPermission[];
	String storagePermission[];
	Uri imageuri;


	TextView click;


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


		// The text and image view 
		// are being initialised here.
		click = findViewById(R.id.click);
		userpic = findViewById(R.id.set_profile_image);


		// granting access to the camera and gallery
		cameraPermission = new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE};
		storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};


		// After selecting words,
		// we will have the option to select
		// an image from the camera or gallery .
		click.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				showImagePicDialog();
			}
		});
	}


	private void showImagePicDialog() {
		String options[] = {"Camera", "Gallery"};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Pick Image From");
		builder.setItems(options, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (which == 0) {
					if (!checkCameraPermission()) {
						requestCameraPermission();
					} else {
						pickFromGallery();
					}
				} else if (which == 1) {
					if (!checkStoragePermission()) {
						requestStoragePermission();
					} else {
						pickFromGallery();
					}
				}
			}
		});
		builder.create().show();
	}


	// here we are checking if we have storage permissions or not
	private Boolean checkStoragePermission() {
		boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
		return result;
	}


	// below we request for gallery permission
	private void requestStoragePermission() {
		requestPermissions(storagePermission, STORAGE_REQUEST);
	}


	// below we are checking for camera permission
	private Boolean checkCameraPermission() {
		boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
		boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
		return result && result1;
	}


	// below we are requesting for camera permission
	private void requestCameraPermission() {
		requestPermissions(cameraPermission, CAMERA_REQUEST);
	}
	// requesting, if not granted, 
	// permission for the camera and gallery
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		switch (requestCode) {
			case CAMERA_REQUEST: {
				if (grantResults.length> 0) {
					booleancamera_accepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
					booleanwriteStorageaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
					if (camera_accepted&&writeStorageaccepted) {
						pickFromGallery();
					} else {
						Toast.makeText(this, "Please Enable Camera and Storage Permissions", Toast.LENGTH_LONG).show();
					}
				}
			}
			break;
			case STORAGE_REQUEST: {
				if (grantResults.length> 0) {
					booleanwriteStorageaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
					if (writeStorageaccepted) {
						pickFromGallery();
					} else {
						Toast.makeText(this, "Please Enable Storage Permissions", Toast.LENGTH_LONG).show();
					}
				}
			}
			break;
		}
	}


	// Here, we'll choose an image from the camera or gallery.
	private void pickFromGallery() {
		CropImage.activity().start(MainActivity.this);
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, @Nullable 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) {
				Uri resultUri = result.getUri();
				Picasso.with(this).load(resultUri).into(userpic);
			}
		}
	}
}

Output:

How to Crop Image from Camera and Gallery in Android How to Crop Image from Camera and Gallery in Android How to Crop Image from Camera and Gallery in Android

Related Topics

Android Studio Resources

To build an outstanding Android application there are many items that you need to use. Aside from the coding of your application, you need to handle various resources such as...

5 minutes read.

Different Ways to Create aar File in Android Studio

A file called an Android archive file (*.aar) can be created using Android Studio and comprises classes and methods that use related files and classes for Android. The Android library...

4 minutes read.

Android Date picker example

How to pick date from the user in Android? Write an android example to pick date from the user and display it. Android provides control for the user to pick a date...

3 minutes read.

ImageView Widget in Android

What you should already KNOW? You should be familiar with: 1) Creating, building, and running apps in Android Studio 2) Basics of android widgets Explanation: Image View widget is used to insert the image...

2 minutes read.

Android Time picker example

How to pick Time from the user in android? Write an android example to pick Time from the user and display the date to the user. Android provides controls for the user...

3 minutes read.

Button Widget in Android Tutorial

Explanation: Button is a widget under Buttons section which is used to execute specific code. Example: XML file: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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">     <Button         android:id="@+id/button"         android:layout_width="wrap_content"    ...

1 minute read.

Android GridView

Theview group that displays items in a two-dimensional scrolling grid is called GridView. The data isadded into this grid layout from anArray List or database. The adapter class isutilized to...

4 minutes read.

Android Toast

Android is one of the most successful operating systems available in today's world. It is an open-source phone platform, compatible with almost all the devices. There are numerous features and...

3 minutes read.

How to insert the mobile number on an android application using EditText

Number Insertion in android application: Sometimes while dealing with numbers, we don't want to insert any string inside an number so, we premiliary define an EditText so we externally specify...

2 minutes read.

How to show image on an android application

ImageView Widget in Android What you should already KNOW? You should be familiar with: 1) Creating, building, and running apps in Android Studio 2) Basics of android widgets   Explanation: Image View widget is used...

2 minutes read.

How to Update Gradle in Android Studio?

The Android Gradle plugin adds a number of features that are unique to develop Android apps to the Gradle build system, which is the foundation of the Android Studio development...

2 minutes read.

Dashboard UI Design in Android

One of the essential components that draw the user’s attentions into the application's operation is the dashboard design. It offers details on the application's general functionality in one location. Imagine...

11 minutes read.

Difference between android developer and web

From a small business to a big firm, every organization in the world of technology requires a digital market presence and only mobile applications and websites/web applications provide for digital...

4 minutes read.

How to Generate QRCode in Android?

Many apps use QR codes to show data in a way that is machine-readable. Data is represented using these codes in a secure manner such that only computers, not humans,...

4 minutes read.

AdapterViewFlipper in Android with Example

The AdapterViewFlipper class, a subclass of the ViewAnimator class, is what we use to switch from two or multiple views when only one is present at a time. The AdapterViewFlipper...

10 minutes read.

Broadcast Receiver in Android with Example

When a device wakes up, receives a message, receives an incoming call, switches to aeroplane mode, or initiates any other system-wide action, it is said to have been broadcast in...

5 minutes read.

How to insert an email in android application in android version 8

Email Address Insertion It is used to insert email adrress from the user in the android application.The only point of difference between an EditText and an Emailtext is that EmailText consisits...

1 minute read.

Android ListView

A kind of AdapterView that displays a vertical list of scrollable views, each of which is laid out below each other is called ListView. Using adapters, items are inserted into...

4 minutes read.

Android Studio's Layout Editor

The Layout Editor allows you to efficiently create layouts by dragging UI elements from the Palette into the visual design editor instead of manually creating the layout XML file by...

8 minutes read.

Android Activity

What is an Activity? Android Activity is a screen in the user interface of an Android application. In this way, Android activity is very similar to the desktop application window. An...

4 minutes read.