Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop while selecting from Gallery in Android 4.4

Since Android 4.4, when you launch and Intent of the type Intent.ACTION_GET_CONTENT, instead of choosing between Gallery, Dropbox, etc, it opens the new Document Browser. This is fine if you just want to open a Image, since this can still be performed the same way than in older APIS. The problem comes when you need to crop the selected image, since the document browser is ignoring the Uri I am passing to it and the crop parameter. This is what I am doing:

void take_photo() {
    File file = null;
    try {
        file = PhotoUtils.createTemporaryFile("picture", ".jpg",
                EditProfileActivity.this);
        file.delete();

    } catch (Exception e) {
        e.printStackTrace();
    }
    photoUri = Uri.fromFile(file);
    Intent galleryIntent= new Intent(Intent.ACTION_GET_CONTENT);
    galleryIntent.setType("image/*");
    galleryIntent.putExtra("crop", "true");
    galleryIntent.putExtra("aspectX", 2);
    galleryIntent.putExtra("aspectY", 2);
    galleryIntent.putExtra("outputX", 1300);
    galleryIntent.putExtra("outputY", 1300);
    galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
    startActivityForResult(galleryIntent, ACTIVITY_SELECT_IMAGE);
}

Then I saved my photoUri to be sure I had it available on return:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (photoUri != null)
        outState.putString("uri", photoUri.toString());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState.containsKey("uri"))
        photoUri = Uri.parse(savedInstanceState.getString("uri"));
}

And then in onActivityResult, I just needed to open an InputStream with photoUri because the galleryIntent had created the file with the croped image.

Now when I do this, the file specified by photoUri in the intent is never created. Is there a new way of doing this?

like image 482
Makerhack Avatar asked Oct 02 '22 04:10

Makerhack


1 Answers

You might want to use the returned intent's data Uri.

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

  if (requestCode == ACTIVITY_SELECT_IMAGE) {

     if(resultCode == RESULT_OK){      
         Uri realUri = intent.getData();   
     }
  }
}

Now since the DocumentsActivity doesn't know how to "crop" anything. You can change your action to: Intent.ACTION_PICK

This will let you get around the DocumentsActivity going directly to the Gallery, or Photos app.

I would suggest you use two Intents, however. One intent to pick a photo, and then one Intent to crop that photo. This is much more reliable since some apps, like the Photos app, don't know what to do with the "crop" extra either.

like image 172
DataDino Avatar answered Oct 13 '22 12:10

DataDino