Home > Mobile >  Crop Intent Not Working in Android Studio
Crop Intent Not Working in Android Studio

Time:03-14

I have a problem regarding cropping image in android studio, whenever I run this cropping code on my device or any other One-plus device, it runs efficiently. But other devices like Redmi, Samsung, Motorola, crash after reaching this cropping part. if I comment out the function call to the cropping function, it runs smoothly on all devices but at cost of non-availability of cropping

public void ImageCropFunction(Uri uri) {

        // Image Crop Code
        try {
            Intent CropIntent = new Intent("com.android.camera.action.CROP");
            Toast.makeText(getContext(),"plz, Crop the Required part",Toast.LENGTH_LONG).show();
            CropIntent.setDataAndType(uri, "image/*");
            CropIntent.putExtra("crop", "true");
            CropIntent.putExtra("outputX", 1024);
            CropIntent.putExtra("outputY", 1024);
            CropIntent.putExtra("return-data", true);
            CropIntent.putExtra("return-uri", uri.toString());
            startActivityForResult(CropIntent, 222);
        }catch (ActivityNotFoundException e) {
        }
    }

CodePudding user response:

Android does not have a CROP Intent. There is no requirement for any device to support that undocumented Intent, let alone with those undocumented extras. There are dozens of libraries for image cropping. Please use one.

CodePudding user response:

What to use


You can use uCrop library.

Implemention


Make sure you have this line in your settings.gradle

maven { url "https://jitpack.io" }

Add it to your build.gradle.

implementation 'com.github.yalantis:ucrop:2.2.6'

Then you should add it to your manifest

<activity
    android:name="com.yalantis.ucrop.UCropActivity"
    android:screenOrientation="portrait"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

How to use


You can crop a image like this

UCrop.of(yourImageUri, whereToSaveYourCroppedImageUri)
    .withAspectRatio(16, 9) // you can change the aspect ratio.
    .withMaxResultSize(maxWidth, maxHeight) // you can add a custom result height for the image. eg 512 X 512
    .start(context); // enter the context and the crop will start.

Get the result


You can fetch the result in the onActivityResult like this

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
        final Uri resultUri = UCrop.getOutput(data);
        // crop is successful
    } else if (resultCode == UCrop.RESULT_ERROR) {
        final Throwable cropError = UCrop.getError(data);
        // crop failed
    }
}

Output


View the output gif from here

  • Related