Iphone – How to take square picture in iphone with avFoundation like in Instagram app

avfoundationcamerainstagramiphoneuiimage

I am taking photo with AVFoundation like here:
http://red-glasses.com/index.php/tutorials/ios4-take-photos-with-live-video-preview-using-avfoundation/

One snippet:

[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
 {
     CFDictionaryRef exifAttachments = CMGetAttachment( imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
     if (exifAttachments)
     {
         // Do something with the attachments.
         NSLog(@"attachements: %@", exifAttachments);
     }
     else
         NSLog(@"no attachments");

     NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
     UIImage *image = [[UIImage alloc] initWithData:imageData];

Picture size as far as i found out is set here:

   AVCaptureSession *session = [[AVCaptureSession alloc] init];  
   session.sessionPreset =AVCaptureSessionPresetMedium; //medium on my iphone4 is 640*480

But here are only few settings possible and cant be set to custom size.

I would like taken pictures to have aspect ratio 1:1 if possible, for example 400×400 pixels (square pictures).
It seems instagram is doing it (or are they cropping images?).

How can i specify the size of taken picture to be square? I know how to change size on the phone, but if the taken picture is not square, the result is not good.

Any idea?

Best Answer

You should probably be resizing your UIImage by creating a new context. Examples below

.....
UIImage *image = [[UIImage alloc] initWithData:imageData];
UIImage *tempImage = nil;
CGSize targetSize = CGSizeMake(400,400);
UIGraphicsBeginImageContext(targetSize);

CGRect thumbnailRect = CGRectMake(0, 0, 0, 0);
thumbnailRect.origin = CGPointMake(0.0,0.0);
thumbnailRect.size.width  = targetSize.width;
thumbnailRect.size.height = targetSize.height;

[image drawInRect:thumbnailRect];

tempImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

// tmpImage is resized to 400x400

Hope this helps !