skip to Main Content

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) {
        }
    }

2

Answers


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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search