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 Tutorial

This Android tutorial will provide you with all the concepts that will be beneficial for both beginners and advanced-level students or candidates. You can learn this tutorial to begin your...

6 minutes read.

Android Navigation Drawer

A sliding menu used to show important links in the Android Application is called Navigation Drawer. The navigation drawermakes it easier to navigate between the fragments. It is not displayed...

5 minutes read.

Android Styles and Themes

Android styles allow you to design the appearance (for example, colors, size, and fonts) of Android UI components from XML resource files. With this method, you only need to set...

5 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.

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.

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.

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.

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.

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 RecyclerView

RecyclerView is a ViewGroup brought to AndroidStudio as successor to ListView and GridView. These are all improvements and are included in the latest v7 support package. It was written to...

8 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 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.

Top 7 Android App Development Books

Do you want to create Android apps but don't know where to start? One should first be familiar with the basics of Android before we discuss these books. With the...

5 minutes read.

What is Android Studio

Android Studio powered by the IntelliJ platform is an integrated development environment (IDE) and is officially recognized for developing androidapplications. Its foundation lies on JetBrains' IntelliJ IDEA and is specialized...

3 minutes read.

Top Programming Languages for Android Development

For mobile apps, there are so many programming languages. You would need to spend days simply researching if you had to pick one from a list of 30 coding languages...

8 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.

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.

Android Project Folder Structure

JetBrains community developed Android Studio, the official IDE (Integrated Development Environment) for Android app development and is freely distributed by Google. After the complete Android Architecture setup, we can construct an...

4 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.