Search code examples
iosobjective-cuiimageuiimagepickercontroller

UIImage won't crop


The user takes a photo using with the camera (UIImagePickerController). However, I can't crop it - or I try, and it returns the exact same photo.

In viewDidAppearI create the image picker controller:

if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
    ipc = [[UIImagePickerController alloc] init];
    ipc.delegate = self;

    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
    ipc.showsCameraControls = NO;

    [[NSBundle mainBundle] loadNibNamed:@"SnapItCameraView" owner:self options:nil];
    self.overlayView.frame = ipc.cameraOverlayView.frame;
    ipc.cameraOverlayView = self.overlayView;
    self.overlayView = nil;
    CGAffineTransform translate = CGAffineTransformMakeTranslation(0.0, 71.0); 
    ipc.cameraViewTransform = translate;
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenHeight = screenRect.size.height;
    CGFloat scaleCamera = screenHeight / 426;

    CGAffineTransform scale = CGAffineTransformScale(translate, scaleCamera, scaleCamera);
    ipc.cameraViewTransform = scale;
    ipc.showsCameraControls = NO;
    ipc.tabBarController.tabBar.hidden = YES;
    ipc.allowsEditing = YES;
    [ipc setAllowsEditing:YES];

    [self presentViewController:ipc animated:YES completion:nil];
}

In didFinishPickingMediaWithInfo

UIImage* theImage = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImageWriteToSavedPhotosAlbum(theImage, nil, nil, nil);             
[self ordinaryCrop:theImage toRect:CGRectMake(20, 0, 250, 250)];
UIImageWriteToSavedPhotosAlbum(theImage, nil, nil, nil);

Cropping:

-(UIImage *)ordinaryCrop:(UIImage *)imageToCrop toRect:(CGRect)cropRect
{
    CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], cropRect);
    UIImage *cropped = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return cropped;
}

But the image is exactly the same after cropping it. I tried the solution in this post, but UIImage* theImage = [info objectForKey:UIImagePickerControllerEditedImage]; returns nil

It's different from [this post][2] because, as the bounty answer points out, 

"The AllowsEditing property simply allows the user to crop to a square if picking an image." The user is not picking an image, and I am not trying to crop to a square specifically. I am trying to crop it at all.


Solution

  • You return cropped from your ordinaryCrop function but you don't do anything with it in didFinishPickingMediaWithInfo, you simply save the original image again.

    What you want is:

    UIImage* theImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImageWriteToSavedPhotosAlbum(theImage, nil, nil, nil);             
    UIImage *croppedImage = [self ordinaryCrop:theImage toRect:CGRectMake(20, 0, 250, 250)];
    UIImageWriteToSavedPhotosAlbum(croppedImage, nil, nil, nil);