Thursday 2 August 2012

Using the Android Crop Intent and Action

Recently I discovered that using standard intents and actions to capture and crop an image was not as straightforward as I had expected. I had assumed there would be a standard, reliable way to launch any apps that can perform a cropping action on images but was unfortunately wrong. Launching the camera is pretty consistent, but cropping an image you have either allowed the user to capture with the camera or choose from the device, for example with a file explorer app or the standard gallery app, is not so easy.

There is a generic action you can use for cropping that is supported on many user devices, but not all of them. The following represents the closest we have to a standard approach to launching a cropping Activity:

Intent croppingIntent = 
 new Intent(""); 

You need to pass various additional data values to the Intent before starting it, and if you want the cropped image to return to your code you need to call the Intent using startActivityForResult, then implement onActivityResult to process the returned cropped image.

So far so good, but unfortunately there are lots of Android vendors whose devices do not support this action. You have two broad options:

  • Only provide your cropping functionality to users whose devices support this Intent
  • Query the user device in order to target specific cropping Activities

If you opt for the first approach, you can include the code in which you call the Intent in a try block, with a catch block outputting an informative error message letting the user know why they can't complete the cropping action. If you opt for the second approach, you have a more complex task in front of you.

See this Stack Overflow post for an example of how to handle differing device crop Activities:
Android Camera Intent with Crop

For an overview of using the basic crop action above, see my tutorial on Mobiletuts+ for more details:
Capture and Crop an Image with the Device Camera

It seems the Android system is plagued a little by this type of issue. When approaching another task recently I found there is a similar problem when attempting to launch the alarm clock app on a user device - a common aim, particularly for clock widget apps.

1 comment:

  1. i also implemented cropping in my apps and i choose the first approach, but the crop result not really good, the resolution is bad, how can i crop an image and get the result same as the original one?