During some downtime at the office I decided to take on an iPhone development project to keep my coding skills fresh. So far the application has been coming along nicely and recently I had to write some code that I thought could help others.
What I needed to do seemed simple, take an image captured from the iPhone camera (or photo gallery) and create a square thumbnail from the image (similar to what you see in the photo browser). The trick is I didn’t want the thumbnail to be skewed so cropping was required. All of the examples I found either focused on cropping only or resizing but I couldn’t find any that did both.
A disclaimer before I post the code, I’m still relatively new to Objective-C so I’m hoping as much to help others as to get some feedback on how I could improve this code. Here is the code which takes a UIImage and crops it to a square then re-sizes it to 64×64 pixels:
// Create a thumbnail version of the image for the event object.
CGSize size = image.size;
CGSize croppedSize;
CGFloat ratio = 64.0;
CGFloat offsetX = 0.0;
CGFloat offsetY = 0.0;
// check the size of the image, we want to make it
// a square with sides the size of the smallest dimension
if (size.width > size.height) {
offsetX = (size.height - size.width) / 2;
croppedSize = CGSizeMake(size.height, size.height);
} else {
offsetY = (size.width - size.height) / 2;
croppedSize = CGSizeMake(size.width, size.width);
}
// Crop the image before resize
CGRect clippedRect = CGRectMake(offsetX * -1, offsetY * -1, croppedSize.width, croppedSize.height);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], clippedRect);
// Done cropping
// Resize the image
CGRect rect = CGRectMake(0.0, 0.0, ratio, ratio);
UIGraphicsBeginImageContext(rect.size);
[[UIImage imageWithCGImage:imageRef] drawInRect:rect];
UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Done Resizing
return thumbnail;
}
I’ve also got a gist of the code here. Any comments or suggestions are welcome!






Very nice, just what I needed.
This works wonderfully. A little HTML snuck into your code on line 11: >
Thanks again!
Awesome code, without any complexity, u rock
Works perfectly. Thanks for posting it!