Saturday, June 20, 2009

Image Picker Sample

The UIImagePickerController provided by Apple is pretty weird. If all you want to do is grab an image, its usage is very straightforward. But, if you want to first allow the user to zoom and crop the photo, the way the controller works is very unintuitive.

Back in February I struggled with trying to use a UIImagePickerController to allow a user to make such cropping adjustments before having the image returned. Fortunately, I found a good starting point with a post on Apple's iPhone developer forum (read it here). Using that sample code and a lot of tinkering with many sample images, I came up with a method that seems to handle the zooming and cropping of arbitrary images.

Someone else was recently writing about how this process is a real pain in the neck, so I figured it might be helpful to others if I posted some sample code.

So, here's a link to a sample XCode project which implements a subclass of UIImagePickerController. The code isn't pretty - I wrote it in a hurry several months ago, it did what I needed at the time, and I don't want to revisit it now. Feel free to do whatever you'd like with it.

My key to understanding the whole image picker crop/zoom process and the cropping info returned is summarized by these comments in my code

"The crop rectangle returned has been scaled relative to the image being 480×640 regardless of the real image dimensions. And, to make matters worse, it’s a virtual 320×320 square centered on the screen rather than being the whole screen. So, we need to rescale the crop rectangle so it matches the original image resolution and so it’s the full screen."

Perhaps this will be useful or helpful to someone else.

The code works with both 2.x and 3.0 of iPhone OS, although the sample project file I include was made specifically for 3.0.


All content copyright © 2009  Brian Stormont, unless otherwise noted.   All rights reserved.