Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

How would i crop an image received from the Camera?

I've looked elsewhere but everything is either too confusing or not working, I am getting an image from the camera and displaying it in an imageView. I just want to crop the original image to 320x320, a square in the middle, kind of like instagram.

here's my code:

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        //a photo was taken/selected!
        self.image = [info objectForKey:UIImagePickerControllerOriginalImage];

        if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            // save the image
            UIImageWriteToSavedPhotosAlbum(self.image, nil, nil, nil);


            self.imageView.image = self.image;
            CGRect frame = self.imageView.frame;
            self.imageView.frame = frame;
            [self.view addSubview:self.imageView];

        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

thanks!

1 Answer

Solved!

            CGSize imageSize = self.image.size;
            CGFloat width = imageSize.width;
            CGFloat height = imageSize.height;
            if (width != height) {
                CGFloat newDimension = MIN(width, height);
                CGFloat widthOffset = (width - newDimension) / 2;
                CGFloat heightOffset = (height - newDimension) / 2;
                UIGraphicsBeginImageContextWithOptions(CGSizeMake(newDimension, newDimension), NO, 0.);
                [self.image drawAtPoint:CGPointMake(-widthOffset, -heightOffset)
                         blendMode:kCGBlendModeCopy
                             alpha:1.];
                self.image = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
            }