Search code examples
androidfileandroid-intentcrop

Android, Pick & Crop image using single startActivityForResult, but retrieving original image URI?


some time ago I managed to make the following code work (thanks to people on the Internet like you, definitely NOT the android documentation...). What it basically does is start the file pick activity (in this case an image) and then jump right to the image crop activity, it then saves the cropped image to the provided file stream.

    File file = new File(saveTo);
    FileOutputStream fs = new FileOutputStream(file);
    fs.close();

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
    intent.setType("image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", maxImageSize);
    intent.putExtra("outputY", maxImageSize);
    intent.putExtra("scale", "true");
    //intent.putExtra("return-data", false);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    intent.putExtra("noFaceDetection", !false);
    intent.putExtra("setWallpaper", false);
    startActivityForResult(intent, CROP_FROM_CAMERA);

First of all, I'd like to make it clear that this works perfectly and I'm not having any problems with this code.

The above code doesn't return any data in its intent. This is because "return-data" extra is commented out by purpose, so that the cropped image is saved directly to the open stream instead of hogging device memory and to prevent ugly behavior with large images.

What I'd like to know is: How can I get the URI of the ORIGINAL file (not the created file\thumbnail) that was chosen and then cropped? Is there a way of doing this without taking apart working code and trying to do this in several steps? (Like first picking the image and then running the cropping activity, storing the original file URI in between)


Solution

  • After some research, I found out that it's bad practice to rely on this intent, since it might be removed or changed in future versions of the Android OS. Guess that's why it was so hard to find any real information about it in the first place. Anyway, I ended up using a custom crop library instead of relying on the internal android intent.