Android Image Crop with Source Code Example

In this tutorial learn how to do Android Image Crop using Library Android Image Cropper Library by developer ArthurHub and make image cropping simple in Android Studio.

In the following example we are building an app that on a button click will prompt the user to select an image from the user gallery and crop the image in constrained or free form Aspect ratio.

Android Image Crop

Getting Started

If you’re building a new Project you can start from here or else skip this step. Create a new Android Studio Project with Blank Activity.

android image crop

Adding the Libraries

To add the Android Image Crop library by developer ArthurHub, add the following lines of code in your build.gradle (app) file:

dependencies {
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.0'
}

To make sure that you sync the updated version of the library, see this project on github here.

Declaring Required Permissions

Google mandates every developer to declare the required permission by an app in AndroidManifest.xml file. For more info on AndroidManifest see here.

For access to user Image Gallery and cropping image, we need to add Read and write permission in AndroidManifest.xml. This will come before the opening of <application> tag.

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

Setting Layout

In main_activity.xml layout file, add two android widgets. First is the upload Button, on clicking which user will be prompted to select an image from its gallery (If required Storage Permissions are obtained) and an ImageView where the image after being cropped will be displayed.

The Code for such a layout is as follows:

<!-- Button -->

    <Button
        android:id="@+id/upload_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/colorAccent"
        android:text="Upload Image"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="20sp" />

<!-- ImageView where the cropped image will be displayed -->

 <ImageView
        android:id="@+id/cropped_img"
        android:padding="20dp"
        android:layout_width="match_parent"
        android:layout_height="350dp"
        android:adjustViewBounds="true"
        android:src="@drawable/default"/>

Coding the Android Image Crop Process

To start with Cropping the image. First, we need to declare a new Activity in our AndroidManifest.xml. However, this is only needed if the default theme of your app doesn’t have an Action Bar.

In AndroidManifest.xml, inside <application> </application> tag, add following lines of code:

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

Go to the MainActivity.java file and link all Objects with Widgets in activitymain.xml using findViewById.

Button uploadBtn;
ImageView croppedImage;

uploadBtn = findViewById(R.id.upload_btn);
croppedImage = findViewById(R.id.cropped_img);

We will now check for the required permission and allow user to select an image from his gallery.

uploadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
                        ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSION_STORAGE);
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSION_STORAGE);
                    showToast("Need Permission to access and upload your Image");
                } else {
                    CropImage.activity()
                            .setGuidelines(CropImageView.Guidelines.ON)
                            .setAspectRatio(1, 1) //You can skip this for free form aspect ratio)
                            .start(MainActivity.this);
                }

            }
        });

Once the user has selected an image, we will send the image for cropping in the built-in CropImageActivity of this Library.

Then override the onActivityResult method in our activity to get crop result.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
    CropImage.ActivityResult result = CropImage.getActivityResult(data);
    if (resultCode == RESULT_OK) {
      Uri resultUri = result.getUri();
    // Set uri as Image in the ImageView:
     croppedImage.setImageUriAsync(uri);
    } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
      Exception error = result.getError();
    }
  }
}

Ta Da! The android image crop feature is not there in your app!

Would like to learn about how to implement a ‘Rate my app in Play Store’ feature in your app? See here.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.