OffRange
OffRange

Reputation: 15

How to crop an image in Android

I want choose a image from the gallery and crop that. I can choose the picture but I can't crop that yet. That is my code I have yet:

public static final int PICK_IMAGE = 0;

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

    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, PICK_IMAGE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    
    if(requestCode == PICK_IMAGE && data != null){
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        cropIntent.setData(data.getData());
        cropIntent.putExtra("crop", "true");
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("outputX", 450);
        cropIntent.putExtra("outputY", 350);
        cropIntent.putExtra("return-data", true);
        startActivityForResult(cropIntent, 1);
    }else if(requestCode == 1){
        Log.d("resultCode", String.valueOf(resultCode));
        Bundle extras = data.getExtras();
        Bitmap bitmap = extras.getParcelable("data");
        ImageView test = findViewById(R.id.test);
        test.setImageBitmap(bitmap);
        test.setScaleType(ImageView.ScaleType.FIT_XY);
    }
    super.onActivityResult(requestCode, resultCode, data);
}

When I start the app I can select a picture. After that my application closes because the data in this line: Bundle extras = data.getExtras(); returns null. And before that the resultCode is 0 which means it canceled. How I can fix that?

Upvotes: 0

Views: 3232

Answers (1)

Ole Pannier
Ole Pannier

Reputation: 3673

You can crop an image using an onActivityResult(). This video shows how to set it up properly with setOnClickListener().

Don't forget to set the implementation in your build.gradle:

implementation 'com.theartofdev.edmodo:android-image-cropper:2.4.+'

Good luck! :)

Upvotes: 1

Related Questions