Take the 2-minute tour ×

So here's where I've made it so far. I am using a UIImage captured from the camera and can crop the center square when in landscape. For some reason this doesn't translate to portrait mode as expected. I'll post my code and logs just for reference.


CGRect squareRect = CGRectMake(offsetX, offsetY, newWidth, newHeight);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], squareRect);
image = [UIImage imageWithCGImage:imageRef scale:1 orientation:image.imageOrientation];

Portrait results (not square):

original image size: {1536, 2048}, with orientation: 3
squareRect: {{0, 256}, {1536, 1536}}
new image size: {1280, 1536}, with orientation: 3 <--- not expected

Landscape results (square):

original image size: {2048, 1536}, with orientation: 1
squareRect: {{256, 0}, {1536, 1536}}
new image size: {1536, 1536}, with orientation: 1

Is this a bug within CGImageCreateWithImageInRect() or am I missing something here?

share|improve this question
add comment

2 Answers

Try something like this:

- (UIImage *)imageByCropping:(UIImage *)image toSize:(CGSize)size
    double x = (image.size.width - size.width) / 2.0;
    double y = (image.size.height - size.height) / 2.0;

    CGRect cropRect = CGRectMake(x, y, size.height, size.width);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    UIImage *cropped = [UIImage imageWithCGImage:imageRef];

    return cropped;

As you see, I don't specify orientation in the call to UIImage imageWithCGImage:. I wonder if that's the problem in your code.

share|improve this answer
I thought that worked at first, but it turns out that I had removed my offsetX and offsetY for a bit while testing your code. I still get the same results, only the orientation is incorrect. –  Uxonith Jan 7 '13 at 22:04
add comment

I was able to accomplish it with something like this:

   UIImage *thisImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
                double x = (thisImage.size.width )/2.0;
                double y = (thisImage.size.height)/2.0;
                mediaImage = [self imageByCropping:thisImage toRect:CGRectMake(x, y, 60, 60)];
                [thisImage release];
share|improve this answer
add comment

Your Answer


